HTML5 画布中的动画 GIF [英] Animated GIF in HTML5 canvas
本文介绍了HTML5 画布中的动画 GIF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 HTML5 中,我如何轻松地在画布中绘制动画 GIF(请不要使用太多复杂的代码)(使用 drawImage 画布中仅显示第一帧)
解决方案
好吧,如果 gif 文件的自动画布动画不可用,您可以尝试使用 sprite-sheets,但这确实需要更多代码.
>
var img_obj = {'来源':空,当前":0,'总帧数':16,宽度":16,高度":16};var img = new Image();img.onload = function () {//图片加载完成时触发.img_obj.source = img;//我们为我们的对象设置图像源.}img.src = 'img/文件名.png';//包含大小为 256x16 的图像//16 帧大小为 16x16function draw_anim(context, x, y, iobj) {//上下文是画布的二维上下文.如果(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;//递增当前帧并确保动画循环}function on_body_load() {//...var canvas = document.getElementById('canvasElement');//<canvas id='canvasElement' width='320' height='200'/>var context = canvas.getContext(2d");setInterval((function (c, i) {返回函数(){draw_anim(c, 10, 10, i);};})(上下文, img_obj), 100);}
这就是我解决问题的方式.希望这有帮助.(已测试)
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)
解决方案
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屋!
查看全文