js实现画布
JavaScript 画布基础实现
创建 HTML5 画布需要结合 <canvas> 元素和 JavaScript 绘图 API。以下是基础实现步骤:
1. HTML 结构设置
<canvas id="myCanvas" width="500" height="300"></canvas>
2. JavaScript 获取画布上下文
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
3. 绘制基础图形

// 绘制矩形(填充)
ctx.fillStyle = 'red';
ctx.fillRect(50, 50, 100, 75);
// 绘制矩形(描边)
ctx.strokeStyle = 'blue';
ctx.lineWidth = 3;
ctx.strokeRect(200, 50, 100, 75);
// 绘制圆形
ctx.beginPath();
ctx.arc(350, 100, 40, 0, Math.PI * 2);
ctx.fillStyle = 'green';
ctx.fill();
高级绘图功能
1. 绘制路径
ctx.beginPath();
ctx.moveTo(100, 150);
ctx.lineTo(200, 250);
ctx.lineTo(50, 250);
ctx.closePath();
ctx.strokeStyle = 'purple';
ctx.stroke();
2. 添加文本
ctx.font = '24px Arial';
ctx.fillStyle = 'black';
ctx.fillText('Hello Canvas', 150, 50);
3. 图像绘制

const img = new Image();
img.src = 'example.png';
img.onload = function() {
ctx.drawImage(img, 300, 150, 100, 100);
};
动画实现
1. 基础动画框架
function animate() {
requestAnimationFrame(animate);
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制动态内容
ctx.fillRect(xPos, 100, 50, 50);
xPos += 1;
}
let xPos = 0;
animate();
2. 交互控制示例
canvas.addEventListener('mousemove', (e) => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(e.clientX - 25, e.clientY - 25, 50, 50);
});
性能优化技巧
- 对于复杂场景,使用
requestAnimationFrame替代setInterval - 离屏渲染:先绘制到隐藏画布再复制到主画布
- 减少不必要的画布状态改变(如频繁修改 fillStyle)
- 使用
transform()替代重复绘制相同图形
常用库扩展
- Three.js:3D 图形库
- Fabric.js:交互式画布库
- Konva.js:分层画布框架
- Paper.js:矢量图形库
完整示例:
<!DOCTYPE html>
<html>
<body>
<canvas id="gameCanvas" width="800" height="600"></canvas>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
function draw() {
ctx.fillStyle = 'rgba(255, 0, 0, 0.5)';
ctx.fillRect(Math.random()*750, Math.random()*550, 50, 50);
requestAnimationFrame(draw);
}
draw();
</script>
</body>
</html>






