Canvas 基础与绘图
约 653 字大约 2 分钟
布欧-Lewyon
2026-05-16
首页 › HTML › HTML5 图形与绘图 › Canvas 基础与绘图
<canvas> 是 HTML5 中用于位图绘制的元素,通过 JavaScript 在画布上绘制图形、文字、图片。
<canvas> 元素
<canvas id="myCanvas" width="400" height="300">
您的浏览器不支持 canvas。
</canvas>| 属性 | 作用 |
|---|---|
width | 画布宽度(默认为 300px) |
height | 画布高度(默认为 150px) |
注意:
width/height是画布本身的尺寸,不是 CSS 尺寸。用 CSS 缩放画布会导致绘制内容失真。
获取绘图上下文
<canvas id="myCanvas" width="400" height="300"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// ctx 就是 CanvasRenderingContext2D 对象
</script>坐标系
Canvas 坐标系的原点 (0, 0) 在画布左上角,x 轴向右,y 轴向下。
基本绘图
矩形
<canvas id="rect" width="300" height="200"></canvas>
<script>
const ctx = document.getElementById('rect').getContext('2d');
// 填充矩形
ctx.fillStyle = '#1890ff';
ctx.fillRect(20, 20, 100, 60);
// 描边矩形
ctx.strokeStyle = '#ff4d4f';
ctx.lineWidth = 3;
ctx.strokeRect(140, 20, 100, 60);
// 清除矩形区域(变为透明)
ctx.clearRect(50, 40, 40, 20);
</script>路径绘图
<canvas id="path" width="300" height="200"></canvas>
<script>
const ctx = document.getElementById('path').getContext('2d');
ctx.beginPath(); // 开始路径
ctx.moveTo(50, 50); // 移动到起点
ctx.lineTo(200, 50); // 画线到 (200, 50)
ctx.lineTo(150, 150); // 画线到 (150, 150)
ctx.closePath(); // 闭合路径(回到起点)
ctx.fillStyle = '#52c41a';
ctx.fill(); // 填充
ctx.strokeStyle = '#333';
ctx.lineWidth = 2;
ctx.stroke(); // 描边
</script>弧线/圆形
<canvas id="arc" width="300" height="200"></canvas>
<script>
const ctx = document.getElementById('arc').getContext('2d');
// arc(x, y, radius, startAngle, endAngle, counterclockwise)
ctx.beginPath();
ctx.arc(100, 100, 50, 0, Math.PI * 2); // 完整圆(0 到 2π)
ctx.fillStyle = '#faad14';
ctx.fill();
// 半圆
ctx.beginPath();
ctx.arc(220, 100, 50, 0, Math.PI); // 0 到 π
ctx.fillStyle = '#ff4d4f';
ctx.fill();
</script>角度以弧度为单位:
弧度 = 角度 × π / 180。
文字
<canvas id="text" width="400" height="200"></canvas>
<script>
const ctx = document.getElementById('text').getContext('2d');
ctx.font = '24px sans-serif';
ctx.fillStyle = '#1890ff';
ctx.fillText('Hello Canvas!', 50, 80); // 填充文字
ctx.font = 'bold 18px serif';
ctx.strokeStyle = '#333';
ctx.strokeText('描边文字', 50, 140); // 描边文字
</script>图形样式
<canvas id="style" width="300" height="200"></canvas>
<script>
const ctx = document.getElementById('style').getContext('2d');
// 颜色
ctx.fillStyle = '#1890ff';
ctx.fillRect(20, 20, 80, 80);
// 渐变色
const gradient = ctx.createLinearGradient(120, 20, 200, 100);
gradient.addColorStop(0, '#ff4d4f');
gradient.addColorStop(1, '#1890ff');
ctx.fillStyle = gradient;
ctx.fillRect(120, 20, 80, 80);
// 透明度
ctx.globalAlpha = 0.5;
ctx.fillStyle = '#52c41a';
ctx.fillRect(70, 70, 80, 80); // 半透明叠加
</script>小结
| API | 作用 |
|---|---|
fillRect(x, y, w, h) | 填充矩形 |
strokeRect(x, y, w, h) | 描边矩形 |
beginPath() / moveTo() / lineTo() | 路径绘制 |
arc(x, y, r, start, end) | 弧线/圆形 |
fillText() / strokeText() | 文字绘制 |
fillStyle / strokeStyle | 颜色/渐变 |
globalAlpha | 透明度 |
上一节:SEO 与结构化数据 下一节:Canvas 动画与图像处理
