js 实现画布
使用 JavaScript 实现画布
创建画布元素
在 HTML 文件中添加一个 <canvas> 元素,并为其指定宽度和高度。可以通过 JavaScript 动态创建或直接在 HTML 中定义。
<canvas id="myCanvas" width="500" height="500"></canvas>
获取画布上下文
通过 JavaScript 获取画布的渲染上下文(2D 或 WebGL),这里以 2D 上下文为例。
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
绘制基本图形
使用上下文对象(ctx)的方法绘制图形,例如矩形、圆形或路径。
绘制矩形
ctx.fillStyle = 'red'; // 设置填充颜色
ctx.fillRect(50, 50, 100, 100); // 绘制填充矩形 (x, y, width, height)
ctx.strokeStyle = 'blue'; // 设置边框颜色
ctx.strokeRect(50, 50, 100, 100); // 绘制边框矩形
绘制圆形

ctx.beginPath();
ctx.arc(200, 200, 50, 0, Math.PI * 2); // (x, y, radius, startAngle, endAngle)
ctx.fillStyle = 'green';
ctx.fill();
ctx.stroke();
绘制路径
通过路径方法绘制自定义形状。
ctx.beginPath();
ctx.moveTo(300, 300); // 起点
ctx.lineTo(400, 300); // 直线到点
ctx.lineTo(350, 400); // 直线到点
ctx.closePath(); // 闭合路径
ctx.strokeStyle = 'purple';
ctx.stroke();
添加文本
在画布上绘制文本。
ctx.font = '20px Arial'; // 设置字体
ctx.fillStyle = 'black'; // 设置文本颜色
ctx.fillText('Hello Canvas', 50, 450); // 绘制填充文本
ctx.strokeText('Hello Canvas', 50, 480); // 绘制边框文本
清除画布
使用 clearRect 方法清除画布内容。

ctx.clearRect(0, 0, canvas.width, canvas.height); // 清除整个画布
动画实现
通过 requestAnimationFrame 实现动画效果。
let x = 0;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height); // 清除画布
ctx.fillRect(x, 100, 50, 50); // 绘制移动的矩形
x += 2; // 更新位置
if (x < canvas.width) {
requestAnimationFrame(animate); // 递归调用
}
}
animate();
事件交互
为画布添加事件监听器,实现交互功能。
canvas.addEventListener('click', (event) => {
const x = event.clientX - canvas.offsetLeft;
const y = event.clientY - canvas.offsetTop;
ctx.fillStyle = 'orange';
ctx.fillRect(x, y, 30, 30);
});
保存画布内容
将画布内容导出为图像。
const dataURL = canvas.toDataURL('image/png'); // 生成 Base64 编码的图像数据
const link = document.createElement('a');
link.href = dataURL;
link.download = 'canvas-image.png'; // 下载文件名
link.click();
注意事项
- 画布默认是透明的,未绘制区域显示为空白。
- 坐标系原点
(0, 0)位于画布左上角。 - 使用
requestAnimationFrame实现动画比setInterval更高效。






