Canvas能实现哪些简单动画效果?

Canvas是一个强大的工具,可以用来创建各种动画效果。以下是一些简单的Canvas动画效果,以及如何使用HTML和JavaScript来实现它们的示例。

移动的矩形示例:

这是一个基础的动画效果,一个矩形在Canvas上从左向右移动。
运行效果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="500" height="500" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>

<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var rect = {x: 0, y: 200, w: 50, h: 50};

function drawRect() {
ctx.fillStyle = "#0095DD";
ctx.fillRect(rect.x, rect.y, rect.w, rect.h);
}

function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height); // clear canvas
rect.x += 1; // move the rectangle 1 pixel to the right
drawRect(); // redraw the rectangle in its new position
requestAnimationFrame(animate); // request another animation frame
}
animate(); // start the animation
</script>

</body>
</html>

尝试一下 »

旋转的矩形示例:

这个动画效果会使一个矩形在Canvas上旋转。

运行效果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="500" height="500" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>

<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var rect = {x: 200, y: 200, w: 50, h: 50};
var angle = 0;

function drawRect() {
ctx.fillStyle = "#0095DD";
ctx.save(); // save the current state of the canvas context
ctx.translate(rect.x + rect.w / 2, rect.y + rect.h / 2); // translate to the center of the rectangle
ctx.rotate(angle); // rotate the context by the current angle
ctx.fillRect(-rect.w / 2, -rect.h / 2, rect.w, rect.h); // draw the rectangle in its new position and rotation state
ctx.restore(); // restore the state before the save() call
}

function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height); // clear the canvas
angle += 0.01; // increment the angle by a small amount each frame
drawRect(); // redraw the rectangle in its new position and rotation state
requestAnimationFrame(animate); // request another animation frame
}
animate(); // start the animation
</script>

</body>
</html>

尝试一下 »