悠悠楠杉
网站页面
正文:
在现代Web开发中,Canvas API是创建动态图形和动画的利器。无论是简单的几何图形还是复杂的交互式动画,Canvas都能轻松应对。本文将带你从零开始掌握Canvas的核心操作,并通过实例代码演示如何实现流畅的动画效果。
首先,需要在HTML中定义一个<canvas>元素作为绘图容器:
html
<canvas id="myCanvas" width="500" height="300"></canvas>
通过JavaScript获取画布上下文(Context),这是所有绘图操作的入口:
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d'); // 获取2D绘图上下文
Canvas提供了丰富的API来绘制基本形状,例如矩形、圆形和路径。
使用fillRect()和strokeRect()分别绘制填充矩形和边框矩形:
ctx.fillStyle = '#3498db'; // 设置填充颜色
ctx.fillRect(50, 50, 100, 80); // 绘制填充矩形 (x, y, width, height)
ctx.strokeStyle = '#e74c3c'; // 设置边框颜色
ctx.strokeRect(200, 50, 100, 80); // 绘制边框矩形
通过beginPath()和arc()绘制圆形:
ctx.beginPath();
ctx.arc(150, 200, 50, 0, Math.PI * 2); // 圆心(x,y), 半径, 起始角, 结束角
ctx.fillStyle = '#2ecc71';
ctx.fill(); // 填充路径
动画的本质是连续帧的快速切换。Canvas中可通过requestAnimationFrame实现高性能动画循环。
以下代码实现了一个水平移动的小球动画:
let x = 50; // 初始位置
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height); // 清空画布
ctx.beginPath();
ctx.arc(x, 150, 30, 0, Math.PI * 2);
ctx.fillStyle = '#9b59b6';
ctx.fill();
x += 2; // 每帧向右移动2像素
if (x > 450) x = 50; // 边界检测
requestAnimationFrame(animate); // 递归调用
}
animate(); // 启动动画
Canvas还支持线性渐变和图像渲染,进一步提升视觉效果。
const gradient = ctx.createLinearGradient(0, 0, 200, 0);
gradient.addColorStop(0, '#f1c40f');
gradient.addColorStop(1, '#e67e22');
ctx.fillStyle = gradient;
ctx.fillRect(50, 250, 200, 50);
通过drawImage()将图片渲染到画布:
const img = new Image();
img.src = 'example.png';
img.onload = () => {
ctx.drawImage(img, 300, 100, 100, 100); // (image, x, y, width, height)
};
requestAnimationFrame:比setInterval更高效。