Fabric.js Canvas上的动画GIF [英] Animated GIF on Fabric.js Canvas

查看:941
本文介绍了Fabric.js Canvas上的动画GIF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开展一个项目,我被要求在fabric.js画布上支持动画GIF。

I'm working on a project where I've been asked to support animated GIF on a fabric.js canvas.

根据 https://github.com/kangax/fabric.js/issues/560 ,我跟着建议使用fabric.util.requestAnimFrame定期渲染。使用此方法可以很好地呈现视频,但GIF似乎没有更新。

As per https://github.com/kangax/fabric.js/issues/560, I've followed the advice to render on regular intervals, using fabric.util.requestAnimFrame. Video renders just fine with this method, but GIFs don't seem to update.

var canvas = new fabric.StaticCanvas(document.getElementById('stage'));

fabric.util.requestAnimFrame(function render() {
    canvas.renderAll();
    fabric.util.requestAnimFrame(render);
});

var myGif = document.createElement('img');
myGif.src = 'http://i.stack.imgur.com/e8nZC.gif';

if(myGif.height > 0){
    addImgToCanvas(myGif);
} else {
    myGif.onload = function(){
        addImgToCanvas(myGif);
    }
}

function addImgToCanvas(imgToAdd){
    var obj = new fabric.Image(imgToAdd, {
        left: 105,
        top: 30,
        crossOrigin: 'anonymous',
        height: 100,
        width:100
    }); 
    canvas.add(obj);
}

JSFiddle here: http://jsfiddle.net/phoenixrizin/o359o11f/

JSFiddle here: http://jsfiddle.net/phoenixrizin/o359o11f/

任何建议都将不胜感激!我一直在寻找,但还没有找到可行的解决方案。

Any advice will be greatly appreciated! I've been searching everywhere, but haven't found a working solution.

推荐答案

根据 to specs 关于Canvas 2DRenderingContext drawImage 方法,

According to specs about the Canvas 2DRenderingContext drawImage method,


具体来说,当 CanvasImageSource 对象代表在 HTMLImageElement 中的动画
图像,用户代理必须使用动画的默认
图像(格式定义的图像将在动画时使用
)不支持或被禁用),或者,如果没有
这样的图像,动画的第一帧,为CanvasRenderingContext2D API渲染图像

Specifically, when a CanvasImageSource object represents an animated image in an HTMLImageElement, the user agent must use the default image of the animation (the one that the format defines is to be used when animation is not supported or is disabled), or, if there is no such image, the first frame of the animation, when rendering the image for CanvasRenderingContext2D APIs.

这意味着只会在画布上绘制动画画布的第一帧。

这是因为使用我们对img标签内的动画没有任何控制。

This means that only the first frame of our animated canvas will be drawn on the canvas.
This is because we don't have any control on animations inside an img tag.

而fabricjs基于canvas API,因此受相同规则的约束。

And fabricjs is based on canvas API and thus regulated by the same rules.

然后解决方案是解析动画gif中的所有静止图像并将其导出为精灵表。
由于精灵课程,您可以在fabricjs中轻松制作动画。

The solution is then to parse all the still-images from your animated gif and to export it as a sprite-sheet. You can then easily animate it in fabricjs thanks to the sprite class.

这篇关于Fabric.js Canvas上的动画GIF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆