In Web development, GIF animation effects can be seen everywhere, such as loading, GIF images of people running, etc., so how to achieve these? In fact, the realization of the principle is very simple, in short, these so-called animation is a frame by frame of the picture after a period of time interval to make displacement; For example, we make GIF animation in PS, first of all to make the required picture for each frame, and then export the GIF image saved; I believe that PS students can be skilled in the production of a basic GIF animation pictures; In Web development, there are many ways to implement such giFs; Here to provide readers with an idea, is to use HTML5 canvas to achieve animation effects.

Use canvas drawImage to load pictures containing frames into canvas, and then combine with JS to achieve animation

<! DOCTYPE html>

<html><head>

<meta charset=”UTF-8″>

<title> Canvas frame — animation </title>

<style>

*{padding:0; margin:0; }

canvas{display:block; background:white}

</style>

</head>

<body>

<canvas></canvas>

<script>

var imgPic = new Image();

imgPic.src = ‘http://www.cj365.cc/demo/bird/bird.png’;

var canvas = document.querySelector(‘canvas’);

canvas.width = window.innerWidth;

canvas.height = window.innerHeight;

var ctx = canvas.getContext(‘2d’);

imgPic.onload = function () {

drawImg()

}

var i = 0;

var lastTime = new Date().getTime();

var delatime;

var timer = 0;

function drawImg() {

window.requestAnimationFrame(drawImg);

var now = new Date().getTime();

delatime = now – lastTime;

lastTime = now;

timer += delatime;

if (timer > 200) {

i++;

if (i > 7) i = 0;

timer = 0

}

console.log(delatime)

ctx.drawImage(imgPic, i * 140, 0, 140, 85, (canvas.width – 140) / 2, (canvas.height – 85) / 2, 140, 85);

}

</script>

</body>

</html>

The premise of the above method is that there needs to be a picture of a drawn frame, and only with the picture can frame animation be carried out; This method can control the playback, pause and frame rate of animation.