同时出现多个JavaScript超时
我正在开发一个HTML5应用程序,我正在画布上以一定的速度绘制一系列图像,每个动画之间都有一定的超时时间 能够多次使用,我已经为它做了一个函数同时出现多个JavaScript超时,javascript,settimeout,setinterval,Javascript,Settimeout,Setinterval,我正在开发一个HTML5应用程序,我正在画布上以一定的速度绘制一系列图像,每个动画之间都有一定的超时时间 能够多次使用,我已经为它做了一个函数 var imgNumber = 0; var lastImgNumber = 0; var animationDone = true; function startUpAnimation(context, imageArray, x, y, timeOut, refreshFreq) { if (lastImgNumber == 0) last
var imgNumber = 0;
var lastImgNumber = 0;
var animationDone = true;
function startUpAnimation(context, imageArray, x, y, timeOut, refreshFreq) {
if (lastImgNumber == 0) lastImgNumber = imageArray.length-1;
if (animationDone) {
animationDone = false;
setTimeout(playAnimationSequence, timeOut, refreshFreq);
}
context.drawImage(imageArray[imgNumber], x, y);
}
function playAnimationSequence(interval) {
var timer = setInterval(function () {
if (imgNumber >= lastImgNumber) {
imgNumber = 0;
clearInterval(timer);
animationDone = true;
} else imgNumber++;
}, interval);
}
现在在我的主代码中,每次使用正确的参数启动动画时,它都可以正常工作但是当我想在屏幕上同时绘制多个动画,并且每个动画的间隔和速度都不一样时,它就不起作用了强>
startUpAnimation(context, world.mushrooms, canvas.width / 3, canvas.height - (canvas.height / 5.3), 5000, 300);
startUpAnimation(context, world.clouds, 100, 200, 3000, 100);
现在,它在正确的位置显示两个动画,但它们都在第一个调用的动画的间隔和超时处进行动画制作,所以在我的例子中是5000超时和300间隔
我如何解决这个问题,使他们都能独立比赛?我想我需要让它成为一门课或什么的,但我不知道如何解决这个问题。在某些情况下,我甚至需要使用此功能同时显示5个动画
任何帮助都将不胜感激 据我所知,每次调用startUpAnimation都会立即绘制到画布上,因为此执行(您的drawImage(..)调用)未包含在setTimeout或setInterval的回调中。尝试类似的方法
var Class = function () {
this.imgNumber = 0;
this.lastImgNumber = 0;
this.animationDone = true;
}
Class.prototype.startUpAnimation = function(context, imageArray, x, y, timeOut, refreshFreq) {
// if (lastImgNumber == 0) lastImgNumber = imageArray.length-1;
if (this.animationDone) {
this.animationDone = false;
setTimeout(this.playAnimationSequence, timeOut, refreshFreq, this);
}
// context.drawImage(imageArray[imgNumber], x, y);
};
Class.prototype.playAnimationSequence = function (interval, object) {
var that = object; // to avoid flobal this in below function
var timer = setInterval(function () {
if (that.imgNumber >= that.lastImgNumber) {
that.imgNumber = 0;
clearInterval(timer);
that.animationDone = true;
console.log("xxx"+interval);
} else that.imgNumber++;
}, interval);
};
var d = new Class();
var d1 = new Class();
d.startUpAnimation(null, [], 300, 300, 5000, 50);
d1.startUpAnimation(null,[], 100, 200, 3000, 60);
它应该可以工作,您只有一个
imgNumber
、一个lastImgNumber
、一个animationDone
变量,用于两个动画。它应该如何设置任何动画?您每次调用仅绘制一次,间隔仅增加一个变量,但不做其他任何操作。您需要绘制图像。感谢您的回答,但其工作原理与以前相同。d1.startUpAnimation使用d.startUpAnimation的间隔和超时,因此它们仍然以相同的速率和时间制作动画。解决了这个问题!谢谢你的解决方案!