js实现canvas
Canvas 基础使用
在 JavaScript 中创建 Canvas 元素并获取绘图上下文:
const canvas = document.createElement('canvas');
canvas.width = 500;
canvas.height = 500;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
绘制基本图形
绘制矩形:
ctx.fillStyle = 'red';
ctx.fillRect(10, 10, 100, 50);
ctx.strokeStyle = 'blue';
ctx.lineWidth = 2;
ctx.strokeRect(150, 10, 100, 50);
绘制圆形:
ctx.beginPath();
ctx.arc(100, 100, 50, 0, Math.PI * 2);
ctx.fillStyle = 'green';
ctx.fill();
绘制路径
自定义路径绘制:
ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(150, 50);
ctx.lineTo(100, 150);
ctx.closePath();
ctx.stroke();
文本绘制
在 Canvas 上绘制文本:
ctx.font = '20px Arial';
ctx.fillStyle = 'black';
ctx.fillText('Hello Canvas', 200, 200);
ctx.strokeStyle = 'purple';
ctx.strokeText('Stroked Text', 200, 230);
图像操作
加载并绘制图像:
const img = new Image();
img.src = 'image.png';
img.onload = () => {
ctx.drawImage(img, 0, 0, 100, 100);
};
变换操作
实现平移、旋转和缩放:
ctx.save();
ctx.translate(250, 250);
ctx.rotate(Math.PI / 4);
ctx.scale(1.5, 1.5);
ctx.fillStyle = 'orange';
ctx.fillRect(-25, -25, 50, 50);
ctx.restore();
动画实现
使用 requestAnimationFrame 创建动画:
let x = 0;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(x, 100, 50, 50);
x += 1;
if (x > canvas.width) x = 0;
requestAnimationFrame(animate);
}
animate();
事件处理
为 Canvas 添加点击事件:
canvas.addEventListener('click', (e) => {
const rect = canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
ctx.fillRect(x - 25, y - 25, 50, 50);
});
性能优化
离屏 Canvas 技术:
const offscreenCanvas = document.createElement('canvas');
offscreenCanvas.width = 100;
offscreenCanvas.height = 100;
const offscreenCtx = offscreenCanvas.getContext('2d');
// 在离屏 Canvas 上绘制复杂图形
offscreenCtx.fillStyle = 'rgba(0, 0, 255, 0.5)';
offscreenCtx.fillRect(0, 0, 100, 100);
// 将离屏内容绘制到主 Canvas
ctx.drawImage(offscreenCanvas, 0, 0);
高级特性
使用渐变和图案:
// 线性渐变
const gradient = ctx.createLinearGradient(0, 0, 200, 0);
gradient.addColorStop(0, 'red');
gradient.addColorStop(1, 'blue');
ctx.fillStyle = gradient;
ctx.fillRect(10, 300, 200, 50);
// 图案
const patternCanvas = document.createElement('canvas');
const patternCtx = patternCanvas.getContext('2d');
patternCanvas.width = 20;
patternCanvas.height = 20;
patternCtx.fillStyle = '#000';
patternCtx.fillRect(0, 0, 10, 10);
patternCtx.fillRect(10, 10, 10, 10);
const pattern = ctx.createPattern(patternCanvas, 'repeat');
ctx.fillStyle = pattern;
ctx.fillRect(10, 360, 200, 200);
像素操作
获取和修改像素数据:
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const data = imageData.data;
for (let i = 0; i < data.length; i += 4) {
data[i] = 255 - data[i]; // R
data[i + 1] = 255 - data[i + 1]; // G
data[i + 2] = 255 - data[i + 2]; // B
}
ctx.putImageData(imageData, 0, 0);
保存 Canvas 内容
将 Canvas 保存为图像:

function saveCanvas() {
const link = document.createElement('a');
link.download = 'canvas-image.png';
link.href = canvas.toDataURL('image/png');
link.click();
}






