在 Javascript 中预加载图像?没有 jQuery

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17440152/
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-10-27 08:19:45  来源:igfitidea点击:

Preloading images in Javascript? Without jQuery

javascriptimagepreload

提问by CookieGuy

There are several questions about this in the forum, but I couldn't get a good answer for what I need.

论坛中有几个关于此的问题,但我无法得到我所需要的很好的答案。

I am getting into Canvas and Javascript, and I want to preload some images as soon as the game opens. I made an example of the method I wanted to build (and didn't work)

我正在使用 Canvas 和 Javascript,我想在游戏打开后立即预加载一些图像。我举了一个我想要构建的方法的例子(并没有奏效)

I have 3 files: "main.html" where the canvas (there is only one in this example) is declared and I try to load an image, "ImagePreloader.js" where I preload all the images and "Variables.js" where I have my variables.

我有 3 个文件:“main.html”,其中声明了画布(本例中只有一个),我尝试加载图像,“ImagePreloader.js”,我预加载所有图像,“Variables.js”,其中我有我的变量。

Could anyone please help me with this image preloading metod, or suggest me a viable one? I think the image is not loading because I am not using an onLoad() function, which I couldn't understand in the tutorials I read so far (I know how to apply it to an image, but not to an array of images)

任何人都可以帮助我使用此图像预加载方法,或建议我一个可行的方法吗?我认为图像没有加载,因为我没有使用 onLoad() 函数,我在到目前为止阅读的教程中无法理解(我知道如何将其应用于图像,但不知道如何应用于图像数组)

main.html:

主文件:

<!DOCTYPE HTML>
<html>
  <body>
    <canvas id="myCanvas" width="800" height="600"></canvas>

    <script type="text/javascript" src="Variables.js"></script>
    <script type="text/javascript" src="ImagePreloader.js"></script>
    <script>
    // Basic canvas info
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');

    // Draw one of the images. Somehow it doesn't work :(
    context.drawImage(imageArray[3], x, y, width, height);
    </script>
  </body>
</html>

ImagePreloader.js

图像预加载器

// This should preload the images in imageArray[i] with 0 <= i <= 5 ... right?
function preloader() 
 {
     for(var i=0; i<5; i++) 
     {
          imageArray[i].src=images[i];
     }
 } 

Variables.js

变量.js

// array of sources of my images
images = new Array();
images[0]="img1.jpg"
images[1]="img2.jpg"
images[2]="img3.jpg"
images[3]="img4.jpg"
images[4]="img5.jpg"

// Stuff to draw the image
var x = 50;
var y = 50;
var width = 256;
var height = 256;

// Is this actually an array of images?
imageArray = new Image();

Thanks in advance!

提前致谢!

回答by e-sushi

Well, you will want to use a function which loads the images at a certain point, so you might as well try to understand onLoad. It's not that hard to grasp.

好吧,你会想要使用一个在某个点加载图像的函数,所以你不妨尝试了解 onLoad。这并不难理解。

"onload" is a javascript event that occurs immediately after somethingis loaded. In other words: onLoadis like a javascript-native function which triggers when somethingis loaded. That somethingcan be a window (eg: window.onload) or a document. What you want is the document onLoad event, as it triggers when your document is loaded.

"onload" 是一个 javascript 事件,在加载某些内容后立即发生。换句话说:onLoad就像一个 javascript-native 函数,它在加载某些东西时触发。那个东西可以是一个窗口(例如:window.onload)或一个文档。您想要的是文档 onLoad 事件,因为它会在您的文档加载时触发。

Let's provide you with a simple example...

让我们为您提供一个简单的例子......

<body onload="preloadMyImages();">

This tells the browser "when you've loaded the document, run the preloadMyImagesfunction".

这会告诉浏览器“当您加载文档时,运行preloadMyImages函数”。

All you have to do is then use that function to load your images into the client's browser cache.

您所要做的就是使用该功能将您的图像加载到客户端的浏览器缓存中。

function preloadMyImages() 
{
    var imageList = [
        "image.gif",
        "example/image.jpg",
        "whatever/image.png"
    ];
    for(var i = 0; i < imageList.length; i++ ) 
    {
        var imageObject = new Image();
        imageObject.src = imageList[i];
    }
}

That practically wraps it up and provides you with a fully working example. Enjoy!

这实际上将它包装起来,并为您提供了一个完整的示例。享受!

EDIT

编辑

Since - according to your comment - you are looking for some more help, I would like to point you to https://stackoverflow.com/a/1038381/2432317which (as one of many examples) shows how that you can (and probably should - depending on what you're planning do draw on your canvas) use img.onload too.

由于 - 根据您的评论 - 您正在寻找更多帮助,我想向您指出https://stackoverflow.com/a/1038381/2432317它(作为许多示例之一)展示了您如何(和可能应该 - 取决于您计划在画布上绘制的内容)也使用 img.onload。

Yet, as I stated in my comment: it will all depend on where you want to take it. The more you dive into Javascript coding, the more you will understand what's going on. There are several good (partly free) books out there explaining how to code Javascript, use the HTML5 canvas, create preloaders, animations, talk about scopes etc.

然而,正如我在评论中所说:这完全取决于你想把它带到哪里。您越深入研究 Javascript 编码,您就会越了解正在发生的事情。有几本好书(部分免费)解释了如何编写 Javascript、使用 HTML5 画布、创建预加载器、动画、讨论范围等。

A quick check at the big G of search engines turns up ample examples and tutorials too which will be helpfull for you. One of many examples: "How To Draw Images Onto Your HTML5 Canvas" which shows you preloading and looping an animation in a short and crisp tutorial.

快速检查搜索引擎的大 G 也会发现大量的示例和教程,这对您很有帮助。许多示例之一:“如何将图像绘制到 HTML5 画布上”,它在简短明了的教程中向您展示了预加载和循环动画。

But please, don't expect us to code it all for you - it's not going to happen. This is one of the not-so-rare cases where "learning by doing"will actually make you smarter. And if you hit another problem on your way to your final goal, you can always post a new question related to that new problem.

但是请不要指望我们为您编写所有代码 - 这不会发生。这是“边做边学”实际上会让你更聪明的一种并不罕见的情况。如果您在实现最终目标的途中遇到另一个问题,您可以随时发布与该新问题相关的新问题。

回答by sabithpocker

You have to make sure these 5 images are loaded (downloaded doesnt alwaysmean its loaded and ready to use, only onload guarantees that image is ready to use) before you use it.

在使用之前,您必须确保这 5 个图像已加载(下载并不总是意味着它已加载并可以使用,只有 onload 才能保证该图像可以使用)。

So add onload for the images, then count from the onload function and trigger the draw after 5 of them are loaded

因此,为图像添加 onload,然后从 onload 函数计数并在加载 5 个图像后触发绘制

function prefetchImages(sources){
        var images = [];
        var loadedImages = 0;
        var numImages = sources.length;
        for (var i=0; i < numImages; i++) {
            images[i] = new Image();
            images[i].onload = function(){
                if (++loadedImages >= numImages) {
                    //ready draw with my images now
                    drawThePainting();
                }
            };
            images[i].src = sources[i]; //bind onload before setting src bug in some chrome versions
        }
    };

prefetchImages(["1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg"]);

function drawThePainting(){
        // Basic canvas info
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');

    // Draw one of the images. Somehow it doesn't work :(
    context.drawImage(imageArray[3], x, y, width, height);
}

回答by Shinov T

try this

试试这个

put this script in head section
<script type="text/javascript">
    function preload(arrayOfImages) {
      for(i = 0 ; i < arrayOfImages.length ; i++)
         {
     var img = new Image();
             img.src = arrayOfImages[i];
         }
    }

 preload(['img1.png','img2.png']);
</script>