js实现画布
使用Canvas API创建画布
在HTML中通过<canvas>标签创建画布元素,并设置宽度和高度属性:
<canvas id="myCanvas" width="500" height="300"></canvas>
获取画布上下文
通过JavaScript获取CanvasRenderingContext2D对象,这是绘图的核心接口:
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
绘制基本图形
绘制矩形(填充与描边):
ctx.fillStyle = 'red';
ctx.fillRect(50, 50, 100, 75); // 填充矩形
ctx.strokeStyle = 'blue';
ctx.lineWidth = 3;
ctx.strokeRect(200, 50, 100, 75); // 描边矩形
绘制路径(直线/三角形):
ctx.beginPath();
ctx.moveTo(50, 150);
ctx.lineTo(150, 150);
ctx.lineTo(100, 220);
ctx.closePath(); // 自动闭合路径
ctx.fillStyle = 'green';
ctx.fill();
绘制圆形与弧线
使用arc()方法绘制圆形:
ctx.beginPath();
ctx.arc(300, 150, 40, 0, Math.PI * 2);
ctx.fillStyle = 'purple';
ctx.fill();
绘制半圆:
ctx.beginPath();
ctx.arc(400, 150, 40, 0, Math.PI);
ctx.strokeStyle = 'orange';
ctx.stroke();
添加文本
设置字体样式并绘制文字:
ctx.font = '24px Arial';
ctx.fillStyle = 'black';
ctx.fillText('Hello Canvas', 50, 280);
ctx.strokeText('Stroke Text', 250, 280);
图像绘制
加载并绘制图像:
const img = new Image();
img.src = 'image.png';
img.onload = function() {
ctx.drawImage(img, 350, 200, 100, 80);
};
动画实现
使用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) x = 0;
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.fillStyle = 'rgba(0,0,255,0.5)';
ctx.beginPath();
ctx.arc(x, y, 30, 0, Math.PI*2);
ctx.fill();
});
高级特性
使用save()和restore()管理绘图状态:
ctx.save(); // 保存当前状态
ctx.fillStyle = 'yellow';
ctx.fillRect(50, 50, 100, 100);
ctx.restore(); // 恢复之前保存的状态
实现渐变效果:

const gradient = ctx.createLinearGradient(0, 0, 200, 0);
gradient.addColorStop(0, 'red');
gradient.addColorStop(1, 'white');
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 200, 200);






