HTML5 Canvas animation effect implementation principle
Online Demo
The HTML5 canvas can help us quickly achieve simple animation effects. The basic principle is as follows:
Draw a graph and clear it at a certain time to simulate an animation process. You can use context. clearRect (0, 0, x, y) to refresh the graph to be drawn.
The first method is to draw a graph, as follows:
function myAnimation() { ctx.clearRect(0, 0, canvas_size_x, canvas_size_y); if (x_icon < 0 || x_icon > canvas_size_x - size_x) { stepX = -stepX; } if (y_icon < 0 || y_icon > canvas_size_y - size_y) { stepY = -stepY; } x_icon += stepX; y_icon += stepY; ctx.drawImage(anim_img, x_icon, y_icon);}
The preceding method clears the canvas content at a certain time and recalculates the drawing position. If the size of the canvas is exceeded, the coordinates are reversed.
The following is the actual drawing method:
function draw() { var canvas = document.getElementById("canvas"); ctx = canvas.getContext("2d"); anim_img = new Image(size_x, size_y); anim_img.onload = function() { setInterval('myAnimation()', 5); } anim_img.src = 'http://www.gbtags.com/gb/networks/avatars/80x8013d6393f-a44c-4180-8cb6-7bf0e4776283.png';}
The above method defines the image and calls the method for actually drawing the animation!
If you are interested in HTML5 animation rendering or want to learn how to simulate the physical animation effect, please read the following interactive tutorial and believe it will help you better understand the HTML canvas:
Particle Motion effects implemented by HTML5 canvas
Source: HTML5 Canvas animation effect implementation principle