js实现画布
使用Canvas API创建画布
在HTML中通过<canvas>标签创建画布基础结构,需设置宽度和高度属性:
<canvas id="myCanvas" width="500" height="300"></canvas>
通过JavaScript获取画布上下文并设置绘图环境:
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
基本绘图操作
绘制矩形可使用以下方法:
ctx.fillStyle = 'red'; // 设置填充颜色
ctx.fillRect(50, 50, 100, 75); // 绘制填充矩形(x,y,width,height)
ctx.strokeStyle = 'blue'; // 设置描边颜色
ctx.lineWidth = 3; // 设置线宽
ctx.strokeRect(200, 50, 100, 75); // 绘制描边矩形
绘制路径时需使用路径命令:
ctx.beginPath();
ctx.moveTo(100, 150); // 起点
ctx.lineTo(250, 150); // 直线
ctx.arc(200, 200, 50, 0, Math.PI * 2); // 圆形
ctx.closePath(); // 闭合路径
ctx.fill(); // 填充路径
文本与图像处理
绘制文本需设置字体属性:

ctx.font = '24px Arial';
ctx.fillStyle = 'green';
ctx.fillText('Hello Canvas', 150, 100); // 填充文本
ctx.strokeText('Hello Canvas', 150, 130); // 描边文本
加载并绘制图像:
const img = new Image();
img.src = 'image.png';
img.onload = function() {
ctx.drawImage(img, 0, 0, 200, 150); // 绘制缩放图像
};
动画实现
使用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();
高级特性应用
实现粒子系统可创建对象数组:

const particles = [];
for (let i = 0; i < 100; i++) {
particles.push({
x: Math.random() * canvas.width,
y: Math.random() * canvas.height,
size: Math.random() * 5 + 2
});
}
function drawParticles() {
particles.forEach(p => {
ctx.beginPath();
ctx.arc(p.x, p.y, p.size, 0, Math.PI * 2);
ctx.fill();
});
}
添加交互事件监听:
canvas.addEventListener('mousemove', (e) => {
const rect = canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(x - 25, y - 25, 50, 50);
});
性能优化技巧
离屏渲染可提升复杂场景性能:
const offscreen = document.createElement('canvas');
offscreen.width = 200;
offscreen.height = 200;
const offCtx = offscreen.getContext('2d');
// 在离屏画布上预绘制
offCtx.fillRect(0, 0, 200, 200);
// 主画布上快速绘制
ctx.drawImage(offscreen, 0, 0);
使用willReadFrequently属性优化频繁读取操作:
const ctx = canvas.getContext('2d', { willReadFrequently: true });






