**1. 创建 Canvas 元素**
首先需要在 HTML 中添加一个 `<canvas>` 标签:
html
<canvas id="myCanvas" width="400" height="300"></canvas>
**2. 获取绘图上下文**
在 JavaScript 中获取 Canvas 的 2D 上下文:
javascript
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
**3. 绘制直线**
使用 `moveTo()` 和 `lineTo()` 方法定义路径,再通过 `stroke()` 描边。
javascript
// 设置线条样式
ctx.strokeStyle = 'blue'; // 线条颜色
ctx.lineWidth = 5; // 线条宽度
// 绘制第一条直线
ctx.beginPath(); // 开始新路径
ctx.moveTo(50, 50); // 起点坐标
ctx.lineTo(350, 50); // 终点坐标
ctx.stroke(); // 描边
// 绘制第二条直线(无需 beginPath,会延续当前路径)
ctx.strokeStyle = 'red';
ctx.lineWidth = 3;
ctx.moveTo(50, 100);
ctx.lineTo(350, 100);
ctx.stroke();
**4. 绘制矩形**
**方法一:使用路径绘制(需手动描边或填充)**
javascript
ctx.beginPath();
ctx.rect(50, 150, 100, 70); // x, y, width, height
ctx.fillStyle = 'rgba(0, 255, 0, 0.5)'; // 半透明绿色
ctx.fill(); // 填充矩形
ctx.lineWidth = 2;
ctx.strokeStyle = 'black';
ctx.stroke(); // 描边矩形
**方法二:直接填充矩形(更高效)**
javascript
ctx.fillStyle = 'purple';
ctx.fillRect(200, 150, 100, 70); // 直接填充紫色矩形
**方法三:直接描边矩形**
javascript
ctx.strokeStyle = 'orange';
ctx.lineWidth = 4;
ctx.strokeRect(200, 250, 100, 40); // 直接描边橙色矩形
**5. 清除矩形区域**
javascript
ctx.clearRect(100, 200, 50, 30); // 清除指定区域(变为透明)
**6. 完整示例代码**
html
<!DOCTYPE html>
<html>
<head>
<title>Canvas 绘制直线和矩形</title>
</head>
<body>
<canvas id="myCanvas" width="400" height="350"></canvas>
<script>
// 获取 Canvas 和绘图上下文
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// 绘制直线
ctx.strokeStyle = 'blue';
ctx.lineWidth = 5;
ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(350, 50);
ctx.stroke();
ctx.strokeStyle = 'red';
ctx.lineWidth = 3;
ctx.moveTo(50, 100);
ctx.lineTo(350, 100);
ctx.stroke();
// 绘制矩形(使用路径)
ctx.beginPath();
ctx.rect(50, 150, 100, 70);
ctx.fillStyle = 'rgba(0, 255, 0, 0.5)';
ctx.fill();
ctx.lineWidth = 2;
ctx.strokeStyle = 'black';
ctx.stroke();
// 直接填充矩形
ctx.fillStyle = 'purple';
ctx.fillRect(200, 150, 100, 70);
// 直接描边矩形
ctx.strokeStyle = 'orange';
ctx.lineWidth = 4;
ctx.strokeRect(200, 250, 100, 40);
// 清除矩形区域
ctx.clearRect(100, 200, 50, 30);
</script>
</body>
</html>
**7. 效果预览**
上述代码将在 Canvas 上绘制:
- 两条水平直线(蓝色和红色)
- 一个半透明绿色填充的矩形(带黑色边框)
- 一个紫色填充的矩形
- 一个橙色边框的矩形
- 一个被清除的透明区域
**8. 绘图状态管理**
使用 `save()` 和 `restore()` 可以保存和恢复绘图状态(如颜色、线宽等):
javascript
ctx.save(); // 保存当前状态
ctx.fillStyle = 'red';
ctx.fillRect(50, 50, 100, 100);
ctx.restore(); // 恢复之前的状态
ctx.fillRect(200, 50, 100, 100); // 使用恢复后的样式
**9. 更多绘制技巧**
- **圆角矩形**:结合弧线和直线绘制。
- **渐变填充**:使用 `createLinearGradient()` 或 `createRadialGradient()`。
- **阴影效果**:通过 `shadowColor`、`shadowBlur` 等属性设置。
Canvas API 功能强大,可以绘制复杂的图形和动画,适合数据可视化、游戏开发等场景。