Skip to content Skip to sidebar Skip to footer

Draw Image On Canvas

I am trying to put an image on a canvas. I read the following tutorial https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Using_images and tried to do someth

Solution 1:

According to the tutorial, you're supposed to wrap your ctx.drawImage() inside img.onload like so

functiondraw() {
  var ctx = document.getElementById('canvas').getContext('2d');
  var img = newImage();
  img.onload = function() {
    ctx.drawImage(img, 0, 0);
  };
  img.src = '/files/4531/backdrop.png';
}

I hope this helps.

Solution 2:

To add to Hass's answer: If you don't like the onload approach, you can await a Promise, like so:

asyncfunctiondraw() {
  let ctx = document.getElementById("canvas").getContext('2d');
  let url = "https://example.com/image.png";
  let img = newImage();
  awaitnewPromise(r => img.onload=r, img.src=url);
  ctx.drawImage(img, 0, 0);
}

Solution 3:

If you don't like to use Promise or onload you can also use EventListener:

functiondraw() {
  var ctx = document.getElementById('canvas').getContext('2d');
  var img = newImage();
  img.addEventListener('load', function(){
    ctx.drawImage(img, 0, 0);
  });
  img.src = '/files/4531/backdrop.png';
}

Post a Comment for "Draw Image On Canvas"