js实现canvas
Canvas 基础使用
在 JavaScript 中使用 Canvas 需要先获取画布元素并设置其上下文。以下是基本步骤:
// 获取 canvas 元素
const canvas = document.getElementById('myCanvas');
// 获取 2D 渲染上下文
const ctx = canvas.getContext('2d');
绘制简单图形
Canvas 提供了多种绘制图形的方法:
// 绘制矩形
ctx.fillStyle = 'red';
ctx.fillRect(10, 10, 100, 100);
// 绘制圆形
ctx.beginPath();
ctx.arc(150, 75, 50, 0, Math.PI * 2);
ctx.fillStyle = 'blue';
ctx.fill();
绘制路径
路径绘制需要先定义路径,再填充或描边:
ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(150, 50);
ctx.lineTo(100, 150);
ctx.closePath();
ctx.strokeStyle = 'green';
ctx.stroke();
文本绘制
Canvas 支持文本渲染功能:
ctx.font = '30px Arial';
ctx.fillStyle = 'black';
ctx.fillText('Hello Canvas', 50, 200);
图像处理
可以在 Canvas 上绘制图像:
const img = new Image();
img.src = 'image.png';
img.onload = function() {
ctx.drawImage(img, 200, 50, 100, 100);
};
动画实现
通过 requestAnimationFrame 可以实现动画效果:
let x = 0;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(x, 50, 50, 50);
x += 2;
requestAnimationFrame(animate);
}
animate();
事件处理
可以为 Canvas 添加交互事件:
canvas.addEventListener('click', function(event) {
const rect = canvas.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
ctx.fillRect(x-25, y-25, 50, 50);
});
性能优化
对于复杂 Canvas 应用,需要注意性能优化:
- 尽量减少不必要的绘制操作
- 使用离屏 Canvas 进行预渲染
- 合理使用 requestAnimationFrame
- 避免频繁的 Canvas 状态改变
高级特性
Canvas 还支持更高级的功能:
// 渐变
const gradient = ctx.createLinearGradient(0, 0, 200, 0);
gradient.addColorStop(0, 'red');
gradient.addColorStop(1, 'blue');
ctx.fillStyle = gradient;
ctx.fillRect(10, 10, 200, 100);
// 阴影
ctx.shadowColor = 'gray';
ctx.shadowBlur = 10;
ctx.shadowOffsetX = 5;
ctx.shadowOffsetY = 5;
ctx.fillRect(50, 50, 100, 100);
清除画布
清除画布内容的方法:
// 清除整个画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 部分清除
ctx.clearRect(50, 50, 100, 100);






