Load image from url and draw to HTML5 Canvas

后端 未结 3 1620
夕颜
夕颜 2020-12-01 11:27

I am having trouble loading an image from a url in javascript. The code below works, but I don\'t want to have to have the image loaded from html. I want to load the image f

3条回答
  •  不知归路
    2020-12-01 12:13

    In case you want a Promise version instead of the onload approach:

    let ctx = document.querySelector("#myCanvas").getContext("2d");
    
    async function drawImage(url) {
      let img = new Image();
      await new Promise(r => img.onload=r, img.src=url);
      ctx.drawImage(img, 0, 0);
    }
    
    drawImage("https://example.com/image.png");
    

提交回复
热议问题