5 的 canvas 可以用于绘制各种动画,以下是实现动画的一些步骤和关键词:
下面是一个简单的例子,使用 Canvas 绘制一个小球动画:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Canvas Animation</title>
<style>
canvas {
border: 1px solid #ccc;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="400" height="400"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x = canvas.width/2;
var y = canvas.height/2;
var radius = 40;
var dx = 2;
var dy = -2;
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, radius, 0 , Math.PI*2);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
function draw() {
// 清空画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制小球
drawBall();
// 更新小球位置
x += dx;
y += dy;
// 边界检测
if(x + dx > canvas.width-radius || x + dx < radius) {
dx = -dx;
}
if(y + dy > canvas.height-radius || y + dy < radius) {
dy = -dy;
}
}
setInterval(draw, 10);
</script>
</body>
</html>
在该例子中,我们使用了 canvas 上下文对象的 arc() 方法来绘制球。setInterval() 方法实现一个简单的循环来更新小球的位置和重新绘制它。当小球撞上边界时,改变其速度反向移动。
具体地说,我们需要基于每一帧清空画布并重新绘制小球,同时不断更新小球的坐标。要使动画平滑,最好使用 requestAnimationFrame() 做出相应改变。