js 实现画布
使用 Canvas API 绘制基础图形
在 HTML 中创建 <canvas> 元素并设置宽高:
<canvas id="myCanvas" width="400" height="300"></canvas>
通过 JavaScript 获取画布上下文:
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
绘制矩形(填充与描边):
ctx.fillStyle = 'red'; // 设置填充颜色
ctx.fillRect(50, 50, 100, 80); // (x, y, width, height)
ctx.strokeStyle = 'blue'; // 设置描边颜色
ctx.lineWidth = 3; // 线宽
ctx.strokeRect(200, 50, 100, 80);
绘制路径与自定义形状
使用路径绘制三角形:
ctx.beginPath();
ctx.moveTo(100, 150); // 起点
ctx.lineTo(150, 250);
ctx.lineTo(50, 250);
ctx.closePath(); // 闭合路径
ctx.fillStyle = 'green';
ctx.fill();
绘制圆形/圆弧:
ctx.beginPath();
ctx.arc(300, 200, 50, 0, Math.PI * 2); // (x, y, radius, startAngle, endAngle)
ctx.strokeStyle = 'purple';
ctx.stroke();
添加文本与图像
绘制文本:
ctx.font = '24px Arial';
ctx.fillStyle = 'black';
ctx.fillText('Hello Canvas', 50, 30);
ctx.strokeText('Outline Text', 200, 30);
加载并绘制图像:
const img = new Image();
img.src = 'image.png';
img.onload = () => {
ctx.drawImage(img, 250, 150, 100, 100); // (image, x, y, width, 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();
处理用户交互
监听鼠标事件实现绘图板:
let isDrawing = false;
canvas.addEventListener('mousedown', () => isDrawing = true);
canvas.addEventListener('mouseup', () => isDrawing = false);
canvas.addEventListener('mousemove', (e) => {
if (!isDrawing) return;
ctx.lineTo(e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop);
});
保存画布内容
将画布导出为图像:
document.getElementById('saveBtn').addEventListener('click', () => {
const dataURL = canvas.toDataURL('image/png');
const link = document.createElement('a');
link.download = 'drawing.png';
link.href = dataURL;
link.click();
});






