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

function draw() {
  var ctx = document.getElementById('canvas').getContext('2d');
  var img = new Image();
  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:

async function draw() {
  let ctx = document.getElementById("canvas").getContext('2d');
  let url = "https://example.com/image.png";
  let img = new Image();
  await new Promise(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:

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

Post a Comment for "Draw Image On Canvas"