js 实现画布
使用 Canvas API 绘制图形
在 HTML 中创建 <canvas> 元素,并通过 JavaScript 获取其上下文进行绘制:
<canvas id="myCanvas" width="400" height="400"></canvas>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// 绘制矩形
ctx.fillStyle = 'blue';
ctx.fillRect(50, 50, 100, 100);
// 绘制圆形
ctx.beginPath();
ctx.arc(200, 200, 50, 0, Math.PI * 2);
ctx.fillStyle = 'red';
ctx.fill();
绘制路径与线条
通过路径绘制复杂图形或线条:

ctx.beginPath();
ctx.moveTo(100, 100); // 起点
ctx.lineTo(300, 100); // 直线
ctx.lineTo(200, 300); // 直线
ctx.closePath(); // 闭合路径
ctx.strokeStyle = 'green';
ctx.lineWidth = 5;
ctx.stroke();
添加文本与图像
在画布上渲染文本或加载图像:
// 绘制文本
ctx.font = '24px Arial';
ctx.fillStyle = 'black';
ctx.fillText('Hello Canvas', 150, 50);
// 加载图像
const img = new Image();
img.src = 'image.png';
img.onload = () => {
ctx.drawImage(img, 250, 250, 100, 100);
};
实现动画效果
使用 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();
事件交互示例
监听鼠标事件实现交互式绘图:
let isDrawing = false;
canvas.addEventListener('mousedown', () => isDrawing = true);
canvas.addEventListener('mouseup', () => isDrawing = false);
canvas.addEventListener('mousemove', (e) => {
if (!isDrawing) return;
ctx.fillStyle = 'purple';
ctx.fillRect(e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop, 10, 10);
});
导出画布内容
将画布保存为图片:
document.getElementById('saveBtn').addEventListener('click', () => {
const link = document.createElement('a');
link.download = 'canvas-image.png';
link.href = canvas.toDataURL('image/png');
link.click();
});






