draw animation
While the canvas API doesn't directly provide a way to support animations, implementing animations in canvas itself is simple: just keep updating and redrawing the canvas. This continuous update and redraw is called the animation loop, and it is the core logic of all animations.
To implement animation in canvas, you first need to initialize the objects on the canvas. Then, start an animation loop to update the canvas, clear the canvas, repaint the canvas, and request the next new animation frame. The basic principle of Canvas animation is shown in Figure 4‑36:
Figure 4-36 Basic principles of canvas animationNext, let's take a look at the implementation process of canvas animation through a simple example. This instance implements a rotating gossip diagram in an animated way. code show as below:
function clear() {
context.clearRect(0, 0, canvas.width, canvas.height);
}
function rotate() {
context.rotate(Math.PI/30); // 每分钟旋转一周
}
function draw () {
// 绘制白色半圆
context.beginPath();
context.arc(0, 0, 80, 1.5*Math.PI, Math.PI/2, false);
context.fillStyle = "white";
context.closePath();
context.fill();
// 绘制黑色半圆
context.beginPath();
context.arc(0, 0, 80, Math.PI/2, 1.5*Math.PI, false);
context.fillStyle = "black";
context.closePath();
context.fill();
// 绘制黑色小圆
context.beginPath();
context.arc(0, 40, 40, 0, Math.PI*2, true);
context.fillStyle = "black";
context.closePath();
context.fill();
// 绘制白色小圆
context.beginPath();
context.arc(0, -40, 40, 0, Math.PI*2, true);
context.fillStyle = "white";
context.closePath();
context.fill();
// 绘制白色小圆心
context.beginPath();
context.arc(0, -40, 5, 0, Math.PI*2, true);
context.fillStyle = "black";
context.closePath();
context.fill();
// 绘制黑色小圆心
context.beginPath();
context.arc(0, 40, 5, 0, Math.PI*2, true);
context.fillStyle = "white";
context.closePath();
context.fill();
}
function drawStage() {
rotate(); // 更新
clear(); // 清除
draw(); // 重绘
}
window.onload = function(){
canvas = document.getElementById('canvas');
context = canvas.getContext('2d');
context.translate(canvas.width/2, canvas.height/2);
setInterval(drawStage, 100);
};
The above code, when the page is loaded, first initializes, and then calls the setInterval(drawStage, 100) method to start the animation loop. In the animation loop, the drawStage () function is called every 100ms to update the canvas, clear the canvas, Repaint the action of the canvas for animation effects. The running result is shown in Figure 4-37:
Figure 4-37 Rotated Bagua DiagramOf course, this is just to demonstrate the principle of implementing animation, so the example is relatively simple. In fact, animations in Canvas can be simple or complex. Simple or complex, the basic principles are exactly the same.