javascript - Canvas .gif 动画

标签 javascript html canvas

我知道您不能简单地在 Canvas 上使用 .gif,所以我想先绘制图像,然后清除图像,然后间隔大约半秒,然后再绘制下一张图像,依此类推。

现在这就是我所做的,但我不确定间隔是否正确,因为我希望屏幕上的所有其他内容都按原样移动,甚至此时正在运行其他动画。 (想想游戏中的爆炸)

我试过了,但是间隔似乎不起作用,它只是一个接一个地绘制所有内容并清除最后一个,所以你什么都看不到。

var wide = 70;
var high = 70;


ctxExplosion.drawImage(spriteImage,0,1250,wide,high,100,100,wide,high);
setInterval(500);  
ctxExplosion.clearRect(0,0,canvasWidth,canvasHeight);

ctxExplosion.drawImage(spriteImage,77,1250,wide,high,100,100,wide,high);
setInterval(500);  
ctxExplosion.clearRect(0,0,canvasWidth,canvasHeight);

ctxExplosion.drawImage(spriteImage,150,1250,wide,high,100,100,wide,high);
setInterval(500);  
ctxExplosion.clearRect(0,0,canvasWidth,canvasHeight);

ctxExplosion.drawImage(spriteImage,232,1250,wide,high,100,100,wide,high);
setInterval(500);  
ctxExplosion.clearRect(0,0,canvasWidth,canvasHeight);

我希望它像动画一样显示,但也不希望图层的清除干扰当时发生的其他爆炸。有什么办法解决这个问题吗?

最佳答案

这是因为您没有正确使用 setInterval。 setInterval 有 2 个参数,一个在指定时间运行的函数,以及等待时间。

你说的是:

  • 画出我的形象
  • 半秒内什么都不做
  • 清除我的图像
  • ...等等...

例如,您可以这样做:

/* Takes an array of offsets, and returns an interval timer representing the current animation*/
makeExplosion = function(offsetArray, frameRate) {
    var currentFrame = 0, interval = null;

    var animFunc = function() {
        ctxExplosion.clearRect(0,0,canvasWidth,canvasHeight);
        ctxExplosion.drawImage(spriteImage,offsetArray[currentFrame],1250,wide,high,100,100,wide,high);

        currentFrame++;
        if (interval && (currentFrame > offsetArray.length)) {
            clearInterval(interval); 
        }
    }

    interval = setInterval(animFunc, frameRate);

    return interval;
}

这将运行您的动画,并返回一个间隔对象,以便您可以根据需要尽快取消动画。这只是一个示例,您需要传入 widehigh 变量,或者对它们执行一些操作以确保它们已定义。

我还没有测试代码,但它应该接近工作。

关于javascript - Canvas .gif 动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16942702/

相关文章:

javascript - 将内容添加到 div 会导致它移动?

使用 Jquery 的 Javascript 数组到 mysql 数据库

jquery - 设置 fabric js Canvas 的 100% 高度和宽度

javascript - HTML5 Canvas 中的 fillText 字体不会更改默认值

使用条件运算符声明数组元素的 Javascript 行为异常?

javascript - 形状的模糊/阴影与 d3.js 原生 react

php - 从页面上的mysql中清除所有显示的记录

html - Floated Div 正在外出并位于 Outline-container 下方

javascript - 确定是否单击了 Google Chrome 打印预览中的打印/取消按钮

javascript - 如何改进这段代码,转换字符串