加载图像同步的JavaScript图像、加载、JavaScript

2023-09-10 13:27:14 作者:再TMD酷一回

我需要同步加载图像,这是我需要的,直到图像加载到暂停执行的JavaScript。由于image.onload是异步的,图像被载入前主函数将返回。

I need to load an image synchronously, that is I need to pause execution of javascript until the image is loaded. Since image.onload is asynchronous, the main function will return before the image is loaded.

我用的帆布,如果图像加载,并因此得出面前的主要函数返回,在画布上其他事情将映像之前绘制。这并不工作,因为在画布上绘制的顺序是非常重要的!

I am using canvas, and if the main function returns before the image is loaded, and therefore drawn, other things in the canvas will be drawn before the image. This does not work because the order of drawing on a canvas is very important!

这是我一直在做:

var img = new Image();
img.onload = function() {
    //image drawing code here
}
img.src = "blahblahblah";
//function returns here, and other drawing code happens before image is drawn

有没有办法做到这一点同步进行,还是要等到图像从函数返回之前完全加载?

Is there a way to do this synchronously, or to wait until the image is fully loaded before returning from the function?

推荐答案

不能在此被重构解决?

Can't this be solved by refactoring?

裹无论code你需要的图像加载到由调用回调函数后执行(或使该功能的callbak)。

Wrap whatever code you need to execute after the image load into a function invoked by the callback (or make that function the callbak).

我看到你说,如果主函数返回,其他code将执行。你可以用的,太?可以延迟它的执行还是使其依赖于这个onload事件或someother事件?

I see that you say that if the main function returns, other code will execute. Can you wrap that, too? Can you delay it's execution or make it dependent on this onload event or someother event?

您甚至可以动态加载在图像的onload的其他JavaScript code的来源。

You could even dynamically load the source of the other javascript code in the image onload.