HTML5 Canvas动画入门:从基础绘制到炫酷效果全攻略

2026-10-19 0 阅读

HTML5 Canvas 是一个强大的功能,允许我们在网页上绘制图形和动画。无论是简单的图形绘制还是复杂的动画效果,Canvas 都能轻松实现。本文将带您从基础绘制开始,逐步深入,探索 Canvas 的动画制作技巧,让您掌握从基础到炫酷效果的完整过程。

基础绘制

1. 创建 Canvas 元素

首先,我们需要在 HTML 文档中创建一个 Canvas 元素。以下是创建一个 500x500 像素的 Canvas 的基本代码:

<canvas id="myCanvas" width="500" height="500"></canvas>

2. 获取 Canvas 上下文

在 JavaScript 中,我们需要使用 getElementById() 方法获取 Canvas 元素,然后通过调用 getContext() 方法来获取 Canvas 的绘图上下文(2D 或 WebGL)。

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

3. 绘制基本图形

Canvas 上下文提供了多种绘图方法,如 fillRect(), strokeRect(), arc(), fillCircle(), drawImage() 等。以下是一些基础图形绘制的示例:

  • 绘制矩形:
ctx.fillStyle = "#FF0000";
ctx.fillRect(0, 0, 50, 50);
  • 绘制圆形:
ctx.beginPath();
ctx.arc(75, 75, 50, 0, Math.PI * 2, true);
ctx.fill();
  • 绘制图片:
var img = new Image();
img.onload = function() {
  ctx.drawImage(img, 0, 0);
};
img.src = "path/to/image.jpg";

动画制作

1. 使用 requestAnimationFrame()

Canvas 动画的关键在于 requestAnimationFrame() 函数。这个函数可以确保动画以流畅的帧率运行。以下是一个简单的动画示例:

function animate() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.beginPath();
  ctx.arc(100, 100, 10, 0, Math.PI * 2, true);
  ctx.fillStyle = "#FF0000";
  ctx.fill();
  ctx.beginPath();
  ctx.arc(100, 100, 20, 0, Math.PI * 2, true);
  ctx.fillStyle = "#FF0000";
  ctx.fill();
  // ...
  requestAnimationFrame(animate);
}
animate();

2. 变化动画效果

通过改变动画中的变量,可以实现更丰富的动画效果。以下是一些示例:

  • 旋转动画:
var angle = 0;
function animate() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.save();
  ctx.translate(100, 100);
  ctx.rotate(angle);
  ctx.fillStyle = "#FF0000";
  ctx.fillRect(-25, -25, 50, 50);
  ctx.restore();
  angle += 0.01;
  requestAnimationFrame(animate);
}
animate();
  • 弹跳动画:
var x = 0;
var y = 0;
var vy = 5;
function animate() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.beginPath();
  ctx.arc(x, y, 10, 0, Math.PI * 2, true);
  ctx.fillStyle = "#FF0000";
  ctx.fill();
  y += vy;
  if (y > canvas.height) {
    vy = -vy;
  }
  requestAnimationFrame(animate);
}
animate();

炫酷效果

1. 实现阴影和透明度

阴影和透明度可以让动画更加生动。以下是一些示例:

  • 阴影效果:
ctx.beginPath();
ctx.arc(100, 100, 50, 0, Math.PI * 2, true);
ctx.fillStyle = "#FF0000";
ctx.shadowColor = "#000000";
ctx.shadowBlur = 10;
ctx.fill();
  • 透明度效果:
ctx.fillStyle = "rgba(255, 0, 0, 0.5)";
ctx.fillRect(0, 0, 100, 100);

2. 使用滤镜效果

Canvas 支持多种滤镜效果,如灰度、反色、亮度等。以下是一些示例:

  • 灰度效果:
ctx.filter = "grayscale(100%)";
ctx.drawImage(img, 0, 0);
  • 反色效果:
ctx.filter = "invert(100%)";
ctx.drawImage(img, 0, 0);

总结

本文介绍了 HTML5 Canvas 动画的基础绘制和动画制作技巧,并展示了如何实现炫酷效果。通过学习本文,您应该能够轻松制作出各种精美的 Canvas 动画。祝您学习愉快!

分享到: