Html 如何在 HTML5 中的画布内播放 gif

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9276594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 22:31:43  来源:igfitidea点击:

How to play gif inside canvas in HTML5

htmlcanvasgif

提问by Namratha

I want to play gif inside a canvas. i hav used the following code. bt it is not working. plz tel me wat is wrong in my code or any other way of doing it.

我想在画布内播放 gif。我使用了以下代码。bt 它不起作用。请告诉我 wat 在我的代码或任何其他方式中是错误的。

var drawingCanvas = document.getElementById('myDrawingCanvas');
if(drawingCanvas.getContext) 
{
    var context = drawingCanvas.getContext('2d');
    var imgObj = new Image();

    imgObj.onload = function () 
    {       
        context.drawImage(imgObj, 0, 0, 1024, 600);
    }
    imgObj.src='HTML Images/Spell Bee/images/mainscreen.gif';
}

回答by rezoner

You cannot as canvas doesn't provide any methods to deal with animated gifs. You should split gif into single frames then create a spritesheetand animate it copying current frame.

你不能,因为画布不提供任何处理动画 gif 的方法。您应该将 gif 拆分为单个帧,然后创建一个spritesheet并将其动画化以复制当前帧。

回答by forresto

You can actually decode the GIF with JavaScript and write the frames to canvas. Check http://slbkbs.org/jsgif/

您实际上可以使用 JavaScript 解码 GIF 并将帧写入画布。检查http://slbkbs.org/jsgif/

回答by Alex Morales

I found an article that answers your question. Basically, when you add an animated gif to a canvas element it displays the exact state the image is at when it's included. So, as rezoner says, you need to create a spritesheet and animate it using javascript.

我找到了一篇文章来回答你的问题。基本上,当您向画布元素添加动画 gif 时,它会显示图像被包含时的确切状态。因此,正如 rezoner 所说,您需要创建一个 spritesheet 并使用 javascript 为其设置动画。