Canvas 是 HTML5 提供的位图绘图 API,可用来创建动态图形、游戏、数据可视化等。以下是入门指南:
1. 基本用法 📌
<canvas id="myCanvas" width="500" height="500"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'lightblue';
ctx.fillRect(0, 0, canvas.width, canvas.height);
</script>
2. 绘图核心功能 🎨
- 绘制形状:
ctx.arc()
(圆形)、ctx.rect()
(矩形) - 绘制文本:
ctx.font = '20px Arial'
+ctx.fillText()
- 图像处理:
ctx.drawImage()
+ 滤镜效果 - 路径操作:
ctx.beginPath()
+ctx.stroke()
3. 动画实现 🔁
通过 requestAnimationFrame()
实现流畅动画:
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制逻辑
requestAnimationFrame(animate);
}
animate();
4. 实用技巧 💡
- 使用
ctx.globalAlpha
调整透明度 - 通过
ctx.strokeStyle
设置线条样式 - 结合
transform()
实现旋转缩放 - 导入图像资源:Canvas 图像处理教程 🖼️
5. 注意事项 ⚠️
- Canvas 是像素级绘图,不支持 CSS 样式
- 大型项目建议使用 WebGL 或 SVG
- 注意性能优化:避免频繁重绘
点击 Canvas 实例演示 查看完整代码示例 📚