js 实现画布
使用JavaScript创建画布
在HTML中创建一个<canvas>元素,并设置宽度和高度属性:
<canvas id="myCanvas" width="500" height="500"></canvas>
获取画布上下文
通过JavaScript获取画布元素并获取2D渲染上下文:
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.fillStyle = 'green';
ctx.fill();
绘制圆形
使用arc方法绘制圆形:
ctx.beginPath();
ctx.arc(200, 200, 50, 0, Math.PI * 2);
ctx.fillStyle = 'purple';
ctx.fill();
添加文本
在画布上绘制文本:
ctx.font = '30px Arial';
ctx.fillStyle = 'black';
ctx.fillText('Hello Canvas', 50, 300);
绘制图像
加载并绘制图像:
const img = new Image();
img.src = 'image.png';
img.onload = function() {
ctx.drawImage(img, 250, 250, 100, 100);
};
动画实现
使用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', function(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);
});
保存画布内容
将画布内容保存为图像:

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






