HTML5 frame animation with canvas

I have a flash animation that I am trying to convert to HTML5. Now I took out all the images. For example, in manual animation, I took images of all hand images. I made a canvas with a basic pattern, but I do not know how to replace these images with a frame.

function draw(){ var canvas = document.getElementById('canvas'); if(canvas.getContext){ // canvas animation code here: var ctx = canvas.getContext('2d'); var lhs = new Image(); lhs.src = "images/left_hnd_1.png"; lhs.onload = function(){ ctx.drawImage(lhs, 293, 137); } } else { // canvas unsupported code here: document.getElementById('girl').style.display = "block"; } } 

Now I have three more frames for this image. left_hnd_2.png, left_hnd_3.png and left_hnd_4.png. I would use one image, but the difference in frames is too big to do it with one image. How can I revive this given the time difference.

Any ideas would be highly appreciated. Thanks!

+4
source share
2 answers

Try the following:

 var imgNumber = 1; var lastImgNumber = 4; var ctx = canvas.getContext('2d'); var img = new Image; img.onload = function(){ ctx.clearRect( 0, 0, ctx.canvas.width, ctx.canvas.height ); ctx.drawImage( img, 0, 0 ); }; var timer = setInterval( function(){ if (imgNumber>lastImgNumber){ clearInterval( timer ); }else{ img.src = "images/left_hnd_"+( imgNumber++ )+".png"; } }, 1000/15 ); //Draw at 15 frames per second 

An alternative, if you have only 4 images, would be to create one huge image with all four in the texture atlas, and then use setTimeout or setInterval to call drawImage() with different parameters, draw different subsets of the image on the canvas.

+6
source

It worked for me too! For some reason, this did not work when I used the OP opening code: function draw(){

However, when I used: window.onload = function draw() { animation plays on the canvas. I also use about 150 PNG images with an alpha channel, so this is a great way to bring β€œvideos” or create composites on an iPad / iPhone. I confirm that it works on the iPad iOS 4.3.

0
source

Source: https://habr.com/ru/post/1336752/


All Articles