绘制基本图形
矩形有三个直达方法:fillRect(x,y,w,h) 填充、strokeRect(x,y,w,h) 描边、clearRect(x,y,w,h) 擦除(动画里每帧清屏全靠它)。填充色由 fillStyle 决定,描边色由 strokeStyle 决定,lineWidth 控制描边粗细。
其他图形都走"路径"模式,固定四步:beginPath() 开新路径 → moveTo()/lineTo() 移动和连线(arc() 画弧)→ closePath() 可选闭合 → fill() 或 stroke() 上色。画圆就是 arc(x, y, r, 0, Math.PI * 2)——从 0 画到 2π 弧度正好一整圈。
常见坑:忘记 beginPath,上一条路径会和新的连在一起;fill 和 stroke 可以对同一路径连用,做出"填充+描边"效果。
本节要点矩形用 fillRect/strokeRect/clearRect 直达;其余图形走 beginPath → 画线/弧 → fill/stroke 四步;圆用 arc 配 2π;每画新图形前记得 beginPath。
JavaScript
var ctx = document.getElementById('cv').getContext('2d'); // 矩形三兄弟:填充 / 描边 / 擦除 ctx.fillStyle = '#e5534b'; ctx.fillRect(20, 20, 80, 50); // 实心矩形 ctx.strokeStyle = '#333'; ctx.lineWidth = 3; ctx.strokeRect(120, 20, 80, 50); // 空心矩形 ctx.clearRect(30, 30, 30, 30); // 擦掉一块 // 直线:路径四步法 ctx.beginPath(); ctx.moveTo(220, 20); // 起点 ctx.lineTo(320, 70); // 终点 ctx.stroke(); // 圆:arc(圆心x, 圆心y, 半径, 起始弧度, 结束弧度) ctx.beginPath(); ctx.arc(60, 140, 30, 0, Math.PI * 2); // 0 到 2π = 整圆 ctx.fillStyle = '#4a9eff'; ctx.fill(); // 填充 ctx.stroke(); // 再描边一次
📚 推荐阅读
来自万象云档的免费在线书籍,点击封面直接阅读




