• <bdo id='KYbkC'></bdo><ul id='KYbkC'></ul>
    1. <small id='KYbkC'></small><noframes id='KYbkC'>

      <legend id='KYbkC'><style id='KYbkC'><dir id='KYbkC'><q id='KYbkC'></q></dir></style></legend>
    2. <i id='KYbkC'><tr id='KYbkC'><dt id='KYbkC'><q id='KYbkC'><span id='KYbkC'><b id='KYbkC'><form id='KYbkC'><ins id='KYbkC'></ins><ul id='KYbkC'></ul><sub id='KYbkC'></sub></form><legend id='KYbkC'></legend><bdo id='KYbkC'><pre id='KYbkC'><center id='KYbkC'></center></pre></bdo></b><th id='KYbkC'></th></span></q></dt></tr></i><div id='KYbkC'><tfoot id='KYbkC'></tfoot><dl id='KYbkC'><fieldset id='KYbkC'></fieldset></dl></div>
      <tfoot id='KYbkC'></tfoot>

      1. 使用 Promise() 在 Web 浏览器上加载图像

        时间:2023-06-20

          <tbody id='ecHEO'></tbody>
      2. <legend id='ecHEO'><style id='ecHEO'><dir id='ecHEO'><q id='ecHEO'></q></dir></style></legend>
          <i id='ecHEO'><tr id='ecHEO'><dt id='ecHEO'><q id='ecHEO'><span id='ecHEO'><b id='ecHEO'><form id='ecHEO'><ins id='ecHEO'></ins><ul id='ecHEO'></ul><sub id='ecHEO'></sub></form><legend id='ecHEO'></legend><bdo id='ecHEO'><pre id='ecHEO'><center id='ecHEO'></center></pre></bdo></b><th id='ecHEO'></th></span></q></dt></tr></i><div id='ecHEO'><tfoot id='ecHEO'></tfoot><dl id='ecHEO'><fieldset id='ecHEO'></fieldset></dl></div>

          <small id='ecHEO'></small><noframes id='ecHEO'>

            <bdo id='ecHEO'></bdo><ul id='ecHEO'></ul>

                • <tfoot id='ecHEO'></tfoot>
                  本文介绍了使用 Promise() 在 Web 浏览器上加载图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

                  问题描述

                  我正在尝试从 这里学习如何用 JavaScript 制作 SuperMario有人可以解释以下函数 LoadImage 的流程吗?

                  I'am trying to learn how to make SuperMario in JavaScript from here Can someone explain flow of the below function LoadImage ?

                  function loadImage(url) {
                          return new  Promise(resolve => {
                              const image = new Image();
                              image.addEventListener('load', () => {
                                  resolve(image);
                              });
                              image.src = url; 
                          });
                  }
                  
                  const canvas = document.getElementById('screen');
                  const context = canvas.getContext('2d');
                  
                  context.fillRect(0,0,50,50);
                  
                  loadImage('/img/tiles.png')
                  .then(image=>{
                      context.drawImage(image,0,0);  // the function LoadImage returns a Promise with image object(which is  a constant)
                  // as parameter and if the promise is fulfilled then the image is drawn. 
                  /
                  });
                  

                  编辑

                  我确实了解如何使用 => 运算符.用于缩短函数长度.

                  I do understand how to use => operator. Which is used to make length of functions smaller.

                  image.addEventListener('load', () => {
                                  resolve(image);
                  

                  上面这行表示在加载图像时承诺已履行.那么这是否意味着执行了以下行,然后事件侦听器正在等待将图像下载到客户端浏览器中?

                  the above line means that the promise is fulfilled when image is loaded. So does this mean that the following line is executed and then the event listener is waiting for the image to be downloaded in client browser ?

                  image.scr = url;
                  

                  下面函数的流程对我来说有点模糊

                  The flow of the below function is a little fuzzy to me

                  function loadImage(url) {
                          return new  Promise(resolve => {
                              const image = new Image();
                              image.addEventListener('load', () => {
                                  resolve(image);
                              });
                              image.src = url; 
                          });
                  

                  编辑 2:

                  好吧,这是一个愚蠢的帖子.是的,因为来自 url 的 IMAGE 被加载到图像对象中,然后事件侦听器启动了 resolve().

                  Okay, this was a stupid post. And yup as the IMAGE from url is loaded in the image object then Event listener fires up the resolve().

                  推荐答案

                  您展示的代码引入了一个异步原语 Promise,它可以被传递并用于访问尚未填充的资源.

                  The code you are showing introduces an asynchronous primitive, Promise, which can be passed around and used to access a resource that hasn't been populated yet.

                  p>

                  在这种情况下,您需要一个完全加载并具有您可以使用的图像数据的 Image.但是,在获取图像数据的网络请求完成之前,您无法访问图像数据.

                  In this case, you want an Image that is fully loaded and has image data that you can use. However, you can't access the image data until a network request finishes that would fetch the image data.

                  例如,这是行不通的:

                  const img = new Image();
                  img.src = "example.com/house.jpg";
                  ctx.drawImage(img, 0, 0); // img isn't done loading yet

                  相反,我们必须等待直到加载完成.有很多方法可以做到这一点,但最常见的约定是使用、回调、Promises 或 async/await.

                  Instead, we have to wait until the loading is done. There are a lot of ways to do that but the most common conventions are to use, callbacks, Promises, or async/await.

                  您展示的方法结合了回调和承诺(非必要).

                  The method that you have shown combines callbacks and Promises (out of necessity).

                  让我们分解代码:

                  /**
                   * Load an image from a given URL
                   * @param {String} url The URL of the image resource
                   * @returns {Promise<Image>} The loaded image
                   */
                  function loadImage(url) {
                    /*
                     * We are going to return a Promise which, when we .then
                     * will give us an Image that should be fully loaded
                     */
                    return new Promise(resolve => {
                      /*
                       * Create the image that we are going to use to
                       * to hold the resource
                       */
                      const image = new Image();
                      /*
                       * The Image API deals in even listeners and callbacks
                       * we attach a listener for the "load" event which fires
                       * when the Image has finished the network request and
                       * populated the Image with data
                       */
                      image.addEventListener('load', () => {
                        /*
                         * You have to manually tell the Promise that you are
                         * done dealing with asynchronous stuff and you are ready
                         * for it to give anything that attached a callback
                         * through .then a realized value.  We do that by calling
                         * resolve and passing it the realized value
                         */
                        resolve(image);
                      });
                      /*
                       * Setting the Image.src is what starts the networking process
                       * to populate an image.  After you set it, the browser fires
                       * a request to get the resource.  We attached a load listener
                       * which will be called once the request finishes and we have
                       * image data
                       */
                      image.src = url;
                    });
                  }
                  
                  /*
                   * To use this we call the loadImage function and call .then
                   * on the Promise that it returns, passing a function that we
                   * want to receive the realized Image
                   */
                  loadImage("example.com/house.jpg").then(houseImage => {
                    ctx.drawImage(houseImage, 0, 0);
                  });

                  老实说,loadImage 函数可能更健壮一些,因为它现在不处理错误.考虑以下增强:

                  In all honesty though, the loadImage function could be a little bit more robust since it doesn't handle errors right now. Consider the following enhancement:

                  const loadImage = (url) => new Promise((resolve, reject) => {
                    const img = new Image();
                    img.addEventListener('load', () => resolve(img));
                    img.addEventListener('error', (err) => reject(err));
                    img.src = url;
                  });
                  
                  loadImage("example.com/house.jpg")
                    .then(img => console.log(`w: ${img.width} | h: ${img.height}`))
                    .catch(err => console.error(err));

                  这篇关于使用 Promise() 在 Web 浏览器上加载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

                  上一篇:HTML5 画布 - 旋转对象而不移动坐标 下一篇:使用新数据更新每个 AJAX 请求的 HTML 画布标签

                  相关文章

                    <bdo id='TkgSY'></bdo><ul id='TkgSY'></ul>

                • <i id='TkgSY'><tr id='TkgSY'><dt id='TkgSY'><q id='TkgSY'><span id='TkgSY'><b id='TkgSY'><form id='TkgSY'><ins id='TkgSY'></ins><ul id='TkgSY'></ul><sub id='TkgSY'></sub></form><legend id='TkgSY'></legend><bdo id='TkgSY'><pre id='TkgSY'><center id='TkgSY'></center></pre></bdo></b><th id='TkgSY'></th></span></q></dt></tr></i><div id='TkgSY'><tfoot id='TkgSY'></tfoot><dl id='TkgSY'><fieldset id='TkgSY'></fieldset></dl></div>

                    1. <legend id='TkgSY'><style id='TkgSY'><dir id='TkgSY'><q id='TkgSY'></q></dir></style></legend><tfoot id='TkgSY'></tfoot>
                    2. <small id='TkgSY'></small><noframes id='TkgSY'>