HTML5 入门教程
Canvas 绘制形状
本教程共 110 篇 · 第 82 篇 · 更新于 2026-07-28 · 约 5 分钟阅读
HTML5HTML5 入门教程Canvas路径圆弧形状
82. Canvas 绘制形状
本节目标:掌握 Canvas 中绘制矩形、路径、圆弧和线条的方法。
上一节我们画了矩形这一种形状。实际上 Canvas 能画的远不止这些,圆形、三角形、曲线都能搞定。
矩形相关方法
Canvas 提供了三个矩形方法:
| 方法 | 作用 |
|---|---|
fillRect(x, y, w, h) | 填充矩形 |
strokeRect(x, y, w, h) | 空心矩形 |
clearRect(x, y, w, h) | 清除矩形区域 |
这三个是最简单的,直接用坐标和尺寸就能画。
路径:绘制任意形状
矩形以外的形状,都要用路径来画。路径的基本流程:
beginPath()开始一条新路径- 用各种方法描述形状
fill()或stroke()填充或描边
ctx.beginPath();
ctx.moveTo(50, 50); // 移动到起点
ctx.lineTo(150, 50); // 画线到 (150, 50)
ctx.lineTo(100, 150); // 画线到 (100, 150)
ctx.closePath(); // 闭合路径(回到起点)
ctx.fillStyle = 'green';
ctx.fill(); // 填充三角形
moveTo 是”抬笔移动”,不画线。lineTo 是”落笔画线”。closePath 把终点连回起点。
绘制圆弧
arc(x, y, radius, startAngle, endAngle) 是画圆和弧线的方法。
ctx.beginPath();
ctx.arc(100, 100, 50, 0, Math.PI * 2); // 完整的圆
ctx.fillStyle = 'orange';
ctx.fill();
参数说明:
x, y:圆心坐标radius:半径startAngle:起始角度(弧度)endAngle:结束角度(弧度)
TipCanvas 用弧度而非角度。
Math.PI是 180 度,Math.PI * 2是 360 度。想转角度用这个公式:弧度 = 角度 * Math.PI / 180。
画一个扇形(半圆):
ctx.beginPath();
ctx.arc(100, 100, 50, 0, Math.PI); // 从 0 到 180 度
ctx.lineTo(100, 100); // 连回圆心
ctx.closePath();
ctx.fillStyle = 'purple';
ctx.fill();
绘制线条
除了 lineTo,还可以用 lineWidth 控制线条粗细:
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineTo(180, 20);
ctx.lineWidth = 5; // 线条粗细
ctx.strokeStyle = 'red'; // 线条颜色
ctx.stroke();
画虚线
setLineDash 可以画虚线:
ctx.setLineDash([10, 5]); // [实线长度, 间隙长度]
ctx.beginPath();
ctx.moveTo(20, 50);
ctx.lineTo(180, 50);
ctx.stroke();
绘制曲线
Canvas 支持两种曲线:
二次贝塞尔曲线
ctx.beginPath();
ctx.moveTo(20, 100);
ctx.quadraticCurveTo(100, 20, 180, 100);
ctx.stroke();
quadraticCurveTo(cpX, cpY, x, y) 中 cpX, cpY 是控制点。
三次贝塞尔曲线
ctx.beginPath();
ctx.moveTo(20, 100);
ctx.bezierCurveTo(60, 20, 140, 20, 180, 100);
ctx.stroke();
bezierCurveTo(cp1X, cp1Y, cp2X, cp2Y, x, y) 有两个控制点,更灵活。
完整示例:画一个小房子
// 房子主体
ctx.fillStyle = '#f5deb3';
ctx.fillRect(100, 150, 120, 100);
// 屋顶
ctx.beginPath();
ctx.moveTo(80, 150);
ctx.lineTo(160, 80);
ctx.lineTo(240, 150);
ctx.closePath();
ctx.fillStyle = '#8b4513';
ctx.fill();
// 门
ctx.fillStyle = '#654321';
ctx.fillRect(140, 200, 40, 50);
// 窗户
ctx.fillStyle = '#87ceeb';
ctx.fillRect(110, 170, 30, 30);
ctx.fillRect(180, 170, 30, 30);
小结
- 矩形用
fillRect、strokeRect、clearRect - 路径用
beginPath开始,fill或stroke结束 arc画圆和弧线,角度用弧度quadraticCurveTo和bezierCurveTo画曲线- 颜色用
fillStyle(填充)和strokeStyle(描边)设置