我正在从事一个项目,要求我在 fabric.js Canvas 上支持动画 GIF。
根据 https://github.com/kangax/fabric.js/issues/560 ,我按照建议使用 fabric.util.requestAnimFrame 定期渲染。使用此方法可以很好地呈现视频,但 GIF 似乎没有更新。
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/
任何建议将不胜感激!我一直在到处搜索,但没有找到可行的解决方案。
最佳答案
根据to specs关于 Canvas 2DRenderingContext drawImage
方法,
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.
这意味着只有动画 Canvas 的第一帧会被绘制在 Canvas 上。
这是因为我们无法控制 img 标签内的动画。
而 fabricjs 是基于 canvas API 的,因此受相同规则的约束。
解决方案是解析动画 gif 中的所有静止图像并将其导出为 sprite-sheet。 由于 sprite class,您可以轻松地在 fabricjs 中为其设置动画。 .
关于javascript - Fabric.js Canvas 上的动画 GIF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28056636/