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

查看:217
本文介绍了Fabric.js 画布上的动画 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 在这里: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.

推荐答案

根据 到规范关于 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 动画中解析所有静止图像并将其导出为精灵表.借助 sprite 类,您可以轻松地在 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 画布上的动画 GIF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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