使用画布在 HTML5 中逐帧动画 [英] Frame by frame animation in HTML5 with canvas
问题描述
我有一个 Flash 动画,我正在尝试将其转换为 HTML5.现在我已经取出了所有的图像.例如在手部动画中,我拍摄了所有手部图像的图像.我已经用基础绘图制作了画布,但我不知道如何逐帧替换这些图像.
I have a flash animation I am trying to convert to HTML5. Now I have taken out all the images. For example in the hand animation, I have taken images of all hand images. I have made the canvas with the base drawing but I don't know how to replace those images frame by 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";
}
}
现在我有这幅图像的三个框架.left_hnd_2.png, left_hnd_3.png &left_hnd_4.png.我会使用一张图像,但帧的差异太大了,无法用一张图像完成.我怎样才能用我想要的时差来制作这个动画.
Now I have three more frame for this image. left_hnd_2.png, left_hnd_3.png & left_hnd_4.png. I would've used one image but the difference in frames is way too much for it to be done with one image. How can I animate this with the time differences I want.
任何想法将不胜感激.谢谢!
Any ideas would be greatly appreciated. Thanks!
推荐答案
试试这个:
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
另一种选择,如果您只有 4 张图像,则可以在纹理图集"中创建一个包含所有四个图像的单个巨大图像,然后使用 setTimeout
或 setInterval
使用不同的参数调用 drawImage()
以将图像的不同子集绘制到画布上.
An alternative, if you only have 4 images, would be to create a single huge image with all four in a 'texture atlas', and then use setTimeout
or setInterval
to call drawImage()
with different parameters to draw different subsets of the image to the canvas.
这篇关于使用画布在 HTML5 中逐帧动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!