gpt4 book ai didi

javascript - 等待 Canvas 动画并获取完成

转载 作者:行者123 更新时间:2023-12-02 22:17:42 24 4
gpt4 key购买 nike

因此,我在对 Canvas 进行动画处理(以创建某种过渡)时获取数据(使用 $.ajax),并且我希望等待获取数据和完成动画以执行其他操作.

我可以轻松等待获取完成,但启动 Canvas 动画的第二个函数正在调用另一个函数,该函数检查动画是否完成。

所以我正在考虑一个 promise ,但我收到一个错误“Uncaught TypeError:resolve is not a function”,这可能是由于 requestAnimationFrame 造成的。

我已经尝试了很多事情(等待等),但似乎无法理解它。

知道为什么或如何以更简单的方式实现这一目标吗?预先非常感谢!

function draw() {

return new Promise( function drawing(resolve, reject) {

ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "rgba(255, 255, 255," + opacity + ")";
ctx.fillRect(0, 0, canvasWidth, canvasHeight) ;

for (var i = particles.length - 1; i >= 0; i--) {

particles[i].drawParticle(img);

if (particles[i].outOfCanvas) {
particles.splice(i, 1);
}

}

fogAnimation = requestAnimationFrame(drawing);

if(particles.length === 0) {
cancelAnimationFrame(fogAnimation);
// below is the error
resolve();
}

});

};

function launchTransition() {

img.onload = function() {
draw().then(function() {
//here is my issue
console.log("done !");
})
};

img.src = particle_image;

// doing more stuff...

}



$('.button').on("click", function() {

fetchData();

launchTransition();

//here I want to wait for the two functions above to be done and do something else


});

最佳答案

您的代码的问题是,当 drawing 函数被 requestAnimationFrame 回调调用时,参数 resolvereject未通过。这就是为什么您会收到错误Uncaught TypeError:resolve is not a function(因为它是未定义)。

为了解决这个问题,我们需要另一个专门用于处理 Promise 的变量(我将其称为 drawingTracker)。我还有一个片段供您了解。

var drawingTracker  = {
resolve: undefined, // this will point to promise resolve
draw() {
return new Promise(resolve, reject) {
this.resolve = resolve // this.resolve (or drawTracker.resolve) is pointing to promise resolve
draw(); // call draw function below
}
},
finish() {
this.resolve(); // will resolve promise
}
};

function draw() { // this function will be called many times by requestAnimationFrame callback
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "rgba(255, 255, 255," + opacity + ")";
ctx.fillRect(0, 0, canvasWidth, canvasHeight) ;

for (var i = particles.length - 1; i >= 0; i--) {

particles[i].drawParticle(img);

if (particles[i].outOfCanvas) {
particles.splice(i, 1);
}

}

fogAnimation = requestAnimationFrame(draw);

if(particles.length === 0) {
cancelAnimationFrame(fogAnimation);
drawingTracker.finish(); // this line will resolve promise without errors
}
};


function launchTransition() {

img.onload = function() {
drawingTracker.draw().then(function() { // this line do the trick!!
console.log("done !");
})
};

img.src = particle_image;

// doing more stuff...

}

希望有帮助。

关于javascript - 等待 Canvas 动画并获取完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59334826/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com