js 实现画布
使用 Canvas API 绘制基础图形
在 HTML 中创建 <canvas> 元素并设置宽度和高度:
<canvas id="myCanvas" width="400" height="400"></canvas>
通过 JavaScript 获取画布上下文并绘制矩形:
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// 绘制填充矩形
ctx.fillStyle = 'red';
ctx.fillRect(10, 10, 100, 100);
// 绘制边框矩形
ctx.strokeStyle = 'blue';
ctx.lineWidth = 5;
ctx.strokeRect(150, 10, 100, 100);
绘制路径与线条
使用路径绘制自定义形状:
ctx.beginPath();
ctx.moveTo(50, 50); // 起点
ctx.lineTo(150, 50); // 水平线
ctx.lineTo(100, 150); // 斜线
ctx.closePath(); // 闭合路径
ctx.stroke();
绘制圆形或圆弧:

ctx.beginPath();
ctx.arc(200, 200, 50, 0, Math.PI * 2); // x, y, 半径, 起始角, 结束角
ctx.fillStyle = 'green';
ctx.fill();
添加文本内容
在画布上绘制文本:
ctx.font = '24px Arial';
ctx.fillStyle = 'purple';
ctx.fillText('Hello Canvas', 50, 300);
ctx.strokeStyle = 'black';
ctx.strokeText('Outline Text', 50, 350);
图像处理与变换
加载并绘制图像:
const img = new Image();
img.src = 'example.jpg';
img.onload = () => {
ctx.drawImage(img, 200, 200, 100, 100); // 图像, x, y, 宽, 高
};
应用变换效果:

ctx.save(); // 保存当前状态
ctx.translate(300, 100); // 移动原点
ctx.rotate(Math.PI / 4); // 旋转45度
ctx.fillRect(0, 0, 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 += 2;
if (x < canvas.width) {
requestAnimationFrame(animate);
}
}
animate();
交互事件处理
监听鼠标事件实现交互:
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.fillText(`Mouse: ${x}, ${y}`, 10, 20);
});
高级特性
使用 getImageData 进行像素操作:
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const data = imageData.data;
// 修改像素数据(RGBA格式)
for (let i = 0; i < data.length; i += 4) {
data[i] = 255 - data[i]; // 红色通道反相
data[i + 1] = 255 - data[i + 1]; // 绿色通道反相
}
ctx.putImageData(imageData, 0, 0);






