HTML5画布中的动画GIF [英] Animated GIF in HTML5 canvas
本文介绍了HTML5画布中的动画GIF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在HTML5中,我可以轻松地绘制(没有太多复杂的代码)一个动画GIF在画布上工作(与drawImage只有第一帧显示在画布上)
In HTML5, how can I draw easily (no too much complex code please) an animated GIF in a canvas that works (with drawImage only first frame is shown in the canvas)
推荐答案
如果没有gif文件的自动化画布动画,您可以尝试使用sprite-sheet,但这确实需要更多的代码。
Well if automated canvas animation of gif files isn't available, you could try using sprite-sheets, but that indeed would require a bit more code.
var img_obj = {
'source': null,
'current': 0,
'total_frames': 16,
'width': 16,
'height': 16
};
var img = new Image();
img.onload = function () { // Triggered when image has finished loading.
img_obj.source = img; // we set the image source for our object.
}
img.src = 'img/filename.png'; // contains an image of size 256x16
// with 16 frames of size 16x16
function draw_anim(context, x, y, iobj) { // context is the canvas 2d context.
if (iobj.source != null)
context.drawImage(iobj.source, iobj.current * iobj.width, 0,
iobj.width, iobj.height,
x, y, iobj.width, iobj.height);
iobj.current = (iobj.current + 1) % iobj.total_frames;
// incrementing the current frame and assuring animation loop
}
function on_body_load() { // <body onload='on_body_load()'>...
var canvas = document.getElementById('canvasElement');
// <canvas id='canvasElement' width='320' height='200'/>
var context = canvas.getContext("2d");
setInterval((function (c, i) {
return function () {
draw_anim(c, 10, 10, i);
};
})(context, img_obj), 100);
}
这是我如何解决这个问题。希望这有帮助。 (测试)
This is how I'd tackle the problem. Hope this has been helpful. (tested)
这篇关于HTML5画布中的动画GIF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文