使用Promise()在网络浏览器上加载图像 [英] loading an image on web browser using Promise()

查看:189
本文介绍了使用Promise()在网络浏览器上加载图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从此处找到方法来学习如何在JavaScript中制作SuperMario。
有人可以解释下面的函数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); //函数
/
}); LoadImage返回一个Promise,它以图像对象(为常数)
//作为参数,如果实现了诺言,则绘制图像。

编辑



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

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

以上一行表示在以下情况下实现了承诺
那么这意味着执行以下行,然后事件侦听器正在等待在客户端浏览器中下载图像吗?

  image.scr = url; 

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

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

编辑2:



好吧,这是一个愚蠢的帖子,是的,因为url中的图像已加载到t中

解决方案

您显示的代码引入了异步原语Promise,可以传递并用于访问尚未填充的资源。


在这种情况下,您需要一个 Image 已完全加载并具有可以使用的图像数据。但是,只有在网络请求完成之后才能访问该图像数据,该请求将提取图像数据。


例如,这将不起作用:


< pre class = snippet-code-js lang-js prettyprint-override> const img = new Image();
img.src = example.com/house.jpg;
ctx.drawImage(img,0,0); // img尚未加载完毕


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


您所展示的方法将回调和Promises(


让我们分解代码:


  / ** 
*从给定的URL加载图像
* @param {String} url图像资源的URL
* @returns {Promise< Image>}已加载的图像
* /
函数loadImage(url){
/ *
*我们将返回一个Promise,当我们.then
*时会给我们一个图像应该完全加载的
* /
返回新的Promise(resolve => {
/ *
*创建要用于
的图像*来保存资源
* /
const image = new Image();
/ *
* Image API甚至在侦听器和回调
中进行交易*我们为 load事件附加了一个侦听器,该事件触发
*当Image完成网络请求并且
*填充有Image数据
* /
image.addEventListener('load',()=> {
/ *
*您必须手动告诉Promise,您已经完成了
*处理异步事务的工作,并且已经准备好
*了,以便它提供附加了回调的任何内容
*到.n的实现价值。我们通过调用
* resolve并将它的实现值
* /
resolve(image)传递给它来实现。
});
/ *
*设置Image.src是启动网络过程
*填充图像的原因。设置后,浏览器将触发
*获取资源的请求。我们附加了一个负载监听器
*,一旦请求完成,就会被调用,并且我们有
*图片数据
* /
image.src = url;
});
}

/ *
*要使用此功能,我们调用loadImage函数并在返回的Promise上调用.then
*,并传递一个我们
*要接收已实现的图像
* /
loadImage( example.com/house.jpg)。then(houseImage => {
ctx.drawImage(houseImage, 0,0);
});




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


  const loadImage =(url)=>新的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));


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. 
/
});

EDIT

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; 
        });

EDIT 2:

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().

解决方案

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.

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.

For example, this won't work:

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

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).

Let's break down the code:

/**
 * 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);
});


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()在网络浏览器上加载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆