2010-06-17 235 views
34

在HTML5中,我怎么能画容易(没有太多复杂的代码,请)在工作画布GIF动画(带的drawImage仅第一帧在画布所示)动画GIF在HTML5画布

+1

这可能是有用的:https://github.com/matt-way/gifuct-js – JoeRocc 2017-08-23 08:19:30

回答

-8

帆布动画不是HTML5规范的一部分。无论是恢复到GIF或考虑呈现SVG或回落到画布/ VML基于JavaScript库:http://raphaeljs.com/

14

我相信你正在寻找http://slbkbs.org/jsgif

遗憾的是,DOM不公开单独的帧的GIF,所以这是通过下载GIF(使用XMLHttpRequest),解析它,然后在<canvas>上绘制它来完成的。

14

那么,如果gif文件的自动化画布动画不可用,您可以尝试使用精灵表,但确实需要更多的代码。

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); 
} 

这就是我如何解决这个问题。希望这有帮助。 (已测试)

+0

这是慈祥的老人。我现在处理它的方式会有所不同。如果您不介意在您的代码中添加新库,请使用这些评论中提出的许多可用备选方案之一。 考虑到ES6的出现,这将更好地重建为具有更多功能的类。 :) – 2016-05-05 07:28:42

1

对于仍然有问题的人,或者不想动态加载其图像或找出需要使用多少帧的人;

在HTML页面上留下动画GIF,设置为在CSS中显示:block,visibility:visible和position:relative。动态地将其置于画布下方,并带有负边距顶部/ Z-索引(或您有什么)。然后设置一个反复调用drawImage的JavaScript定时器,以便根据需要快速刷新图像。

如果图像在DOM中不可见,则drawImage例程无法获取动画的后续帧。如果图像完全位于画布下,则渲染滞后。

+0

你不能像这样分层,除非你把多个画布放在另一个之上 – trinalbadger587 2016-12-25 16:36:40

+0

哦,它在2016年年底发生了变化吗?因为在2014年,我在Chrome和VTC1010上都做得很好。 – Ayelis 2017-03-24 18:12:10

1

那么,正如其他人已经表示,你必须拆分帧动画。我解决问题的方式更多的是个人偏好,但我在GIMP中打开GIF,并使用插件将所有作为单独图层显示的帧转换为精灵图表。然后,我只需要在画布上对精灵进行动画处理,这很容易。

这里是link该插件:d