用 Canvas 代码实现绘制圆角矩形,附完整示例!
当然可以!以下是一个示例代码,使用Canvas绘制一个带有圆角的矩形: ```html <!DOCTYPE html> <html> <head> <title>Canvas圆角矩形</title> </head> <body> <canvas id="myCanvas" width="500" height="500"></canvas> <script> var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); var x = 50; // 矩形左上角的x坐标 var y = 50; // 矩形左上角的y坐标 var width = 200; // 矩形的宽度 var height = 100; // 矩形的高度 var cornerRadius = 20; // 圆角的半径 ctx.beginPath(); ctx.moveTo(x + cornerRadius, y); ctx.lineTo(x + width - cornerRadius, y); ctx.arcTo(x + width, y, x + width, y + cornerRadius, cornerRadius); ctx.lineTo(x + width, y + height - cornerRadius); ctx.arcTo(x + width, y + height, x + width - cornerRadius, y + height, cornerRadius); ctx.lineTo(x + cornerRadius, y + height); ctx.arcTo(x, y + height, x, y + height - cornerRadius, cornerRadius); ctx.lineTo(x, y + cornerRadius); ctx.arcTo(x, y, x + cornerRadius, y, cornerRadius); ctx.closePath(); ctx.lineWidth = 5; // 线宽 ctx.strokeStyle = "black"; // 边线颜色 ctx.fillStyle = "red"; // 填充颜色 ctx.stroke(); // 绘制边线 ctx.fill(); // 绘制填充 </script> </body> </html> ``` 这段代码使用`ctx.arcTo()`方法绘制圆角,通过调整`cornerRadius`变量的值来改变圆角的大小。可以将上述代码复制粘贴到一个HTML文件中,然后在浏览器中打开,就可以看到绘制的圆角矩形啦! ######[AI写代码神器 | 1387点数解答 | 2023-10-05 00:44:58]
- 忻州一中百日誓师大会动画代码揭秘:优化建议与逻辑要点全解析(字节豆包 | 160点数解答 | 2025-02-28 16:18:33)238
- 代码揭秘:如何用 HTML 和 JS 实现炫酷写轮眼动画(字节豆包 | 883点数解答 | 2025-06-25 22:50:24)159
- 功夫忍者挑战代码优化建议与逻辑要点揭秘(字节豆包 | 171点数解答 | 2025-03-08 21:40:11)208
- HTML Canvas 打造超浪漫动画,烟花、星星、亲吻与玫瑰齐登场!(DeepSeek | 116点数解答 | 2025-02-06 20:20:57)266
- 简单下落方块游戏代码分析:优点、改进与注意要点大揭秘!(字节豆包 | 192点数解答 | 2025-03-20 23:42:13)222
- 写轮眼动画代码:从基础实现到优化升级的全解析(字节豆包 | 904点数解答 | 2025-07-05 22:54:34)163
- 写轮眼动画代码:性能问题剖析与优化秘籍大揭秘!(字节豆包 | 929点数解答 | 2025-07-09 12:16:32)158
- 交互式六边形动画代码解析:实现、优化与注意要点(DeepSeek | 255点数解答 | 2025-03-04 17:55:05)224
- HTML 画布绘制爱心代码优化与注意要点揭秘(字节豆包 | 165点数解答 | 2025-03-23 15:00:43)282
- Java实现链表反转:迭代与递归双解法详解及开发实战指南(DeepSeek | 1409点数解答 | 2026-03-15 15:09:29)22
- “九尾狐变美女”HTML 页面搭建:从基础结构到优化要点揭秘 (字节豆包 | 182点数解答 | 2025-02-10 03:35:53)239
- 微型射击游戏代码:优化建议与关键逻辑注意点揭秘(字节豆包 | 173点数解答 | 2025-03-30 11:12:55)195