企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
图示分析(r是半径) ![](https://box.kancloud.cn/178f077e36ad03730a5e39ad656f22f2_330x262.jpg) 一目了然,有过数学基础的应该很容易就能明白。。没有也没关系,大不了直接复制拿走,,,嘿嘿嘿~~~ 下面来封装一下函数 ![](https://box.kancloud.cn/ee94cbce20aaf44a4dfe7d96099d61ff_113x146.jpg) ~~~ // 圆角矩形 function drawRoundRect(x, y, width, height, radius){ ctx.beginPath(); ctx.arc(x + radius, y + radius, radius, Math.PI, Math.PI * 3 / 2); ctx.lineTo(width - radius + x, y); ctx.arc(width - radius + x, radius + y, radius, Math.PI * 3 / 2, Math.PI * 2); ctx.lineTo(width + x, height + y - radius); ctx.arc(width - radius + x, height - radius + y, radius, 0, Math.PI * 1 / 2); ctx.lineTo(radius + x, height +y); ctx.arc(radius + x, height - radius + y, radius, Math.PI * 1 / 2, Math.PI); ctx.closePath(); } drawRoundRect(100, 300, 80, 40, 10); ~~~ 接着先看着整体代码的填充矩形效果 ![](https://box.kancloud.cn/56aab3f45a7d9ce9f0bb7d995420719d_137x74.jpg) ~~~ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>圆角矩形</title> <style> *{margin: 0;padding: 0;} </style> </head> <body> <canvas id="canvas" data-percent="10"></canvas> <script> var $ = document.querySelector.bind(document); var canvas = $('#canvas'), canvasWth = 500; canvasHgt = 500; canvas.width = canvasWth; canvas.height = canvasHgt; canvas.style.backgroundColor = '#999'; var ctx = canvas.getContext('2d'); // 圆角矩形 function drawRoundRect(x, y, width, height, radius){ ctx.beginPath(); ctx.arc(x + radius, y + radius, radius, Math.PI, Math.PI * 3 / 2); ctx.lineTo(width - radius + x, y); ctx.arc(width - radius + x, radius + y, radius, Math.PI * 3 / 2, Math.PI * 2); ctx.lineTo(width + x, height + y - radius); ctx.arc(width - radius + x, height - radius + y, radius, 0, Math.PI * 1 / 2); ctx.lineTo(radius + x, height +y); ctx.arc(radius + x, height - radius + y, radius, Math.PI * 1 / 2, Math.PI); ctx.closePath(); } drawRoundRect(100, 300, 80, 40, 10); ctx.strokeStyle = "#0078AA"; ctx.stroke(); ctx.fillStyle = "#0078AA"; ctx.fill(); </script> </body> </html> ~~~ 再来看下描边矩形效果(稍微改变下radius结果就不一样了) ![](https://box.kancloud.cn/bb833c2fe2a85ae070324e5fba412cee_109x60.jpg) ~~~ // 圆角矩形 function drawRoundRect(x, y, width, height, radius){ ctx.beginPath(); ctx.arc(x + radius, y + radius, radius, Math.PI, Math.PI * 3 / 2); ctx.lineTo(width - radius + x, y); ctx.arc(width - radius + x, radius + y, radius, Math.PI * 3 / 2, Math.PI * 2); ctx.lineTo(width + x, height + y - radius); ctx.arc(width - radius + x, height - radius + y, radius, 0, Math.PI * 1 / 2); ctx.lineTo(radius + x, height +y); ctx.arc(radius + x, height - radius + y, radius, Math.PI * 1 / 2, Math.PI); ctx.closePath(); } drawRoundRect(100, 300, 80, 40, 20); ctx.strokeStyle = "#FFCD44"; ctx.stroke(); ~~~ 是不是很惊喜!可惜到此结束了。。 客观憋屈道: ![](https://box.kancloud.cn/16b344abd78310633c51bf01b0f909a7_151x167.jpg) 那我就吟诗一首聊表歉意吧 ~~~ 送杜少府之任蜀州 唐王勃 城阙辅三秦,风烟望五津。 与君离别意,同是宦游人。 海内存知己,天涯若比邻。 无为在歧路,儿女共沾巾。 ~~~