JS Canvas绘图
学习Canvas API · 难度:进阶 · +15XP
JavaScript Canvas 绘图入门
Canvas(画布)是 HTML5 提供的 2D 绘图 API,通过 JavaScript 在 <canvas> 元素上绘制图形、文字、图像和动画。Canvas 是位图渲染,每个像素都可以独立控制,广泛用于数据可视化、游戏开发、图像处理、动画效果等场景。
Canvas 基础设置
- 在 HTML 中添加
<canvas>元素并设置宽高 - 通过
getContext("2d")获取 2D 渲染上下文 - 使用上下文对象的方法进行绘制
<!-- HTML -->
<canvas id="myCanvas" width="500" height="400"></canvas>
// JavaScript: 获取上下文
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
// 注意:canvas 尺寸通过 width/height 属性设置(不是 CSS 样式)
// CSS 样式会缩放画布而不会改变分辨率
绘制图形
| 功能 | 方法 | 说明 |
|---|---|---|
| 矩形(填充) | fillRect(x, y, w, h) | 绘制填充矩形 |
| 矩形(描边) | strokeRect(x, y, w, h) | 绘制矩形边框 |
| 清除区域 | clearRect(x, y, w, h) | 擦除指定区域 |
| 圆形/弧线 | arc(x, y, r, start, end) | 绘制圆弧 |
| 线条 | moveTo/lineTo | 绘制路径 |
const ctx = document.getElementById("c").getContext("2d");
// 绘制填充矩形
ctx.fillStyle = "blue";
ctx.fillRect(20, 20, 150, 100);
// 绘制描边矩形
ctx.strokeStyle = "red";
ctx.lineWidth = 3;
ctx.strokeRect(200, 20, 150, 100);
// 绘制圆形(使用 arc + 路径)
ctx.beginPath();
ctx.arc(100, 250, 50, 0, Math.PI * 2);
ctx.fillStyle = "green";
ctx.fill();
ctx.strokeStyle = "darkgreen";
ctx.stroke();
// 绘制线条(路径方式)
ctx.beginPath();
ctx.moveTo(50, 350); // 起点
ctx.lineTo(200, 350); // 画线到
ctx.lineTo(125, 380); // 画线到
ctx.closePath(); // 闭合路径
ctx.fillStyle = "orange";
ctx.fill();
ctx.stroke();
绘制文字与渐变
// 绘制文字
ctx.font = "bold 30px Arial";
ctx.fillStyle = "purple";
ctx.textAlign = "center";
ctx.fillText("Hello Canvas!", 250, 50);
ctx.font = "20px serif";
ctx.strokeStyle = "navy";
ctx.strokeText("描边文字", 250, 90);
// 线性渐变
const gradient = ctx.createLinearGradient(300, 120, 450, 220);
gradient.addColorStop(0, "red");
gradient.addColorStop(0.5, "yellow");
gradient.addColorStop(1, "blue");
ctx.fillStyle = gradient;
ctx.fillRect(300, 120, 150, 100);
// 径向渐变
const radGrad = ctx.createRadialGradient(400, 300, 10, 400, 300, 60);
radGrad.addColorStop(0, "white");
radGrad.addColorStop(1, "black");
ctx.fillStyle = radGrad;
ctx.beginPath();
ctx.arc(400, 300, 60, 0, Math.PI * 2);
ctx.fill();