13

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 from a url using pure javascript.

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("imImageId");
ctx.drawImage(img, 0, 0);

3 Answers 3

35

Simple, just create an image object in JavaScript, set the src, and wait for the load event before drawing.

Working Example:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = new Image();
img.onload = function() {
    ctx.drawImage(img, 0, 0);
};
img.src = 'https://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png';
<canvas id="myCanvas"></canvas>

4
  • Prefer img.addEventListener("load", () => ctx.drawImage(img, 0, 0)) over setting onload. Commented Oct 31, 2021 at 10:20
  • @SebastianSimon Can you explain why?
    – holydragon
    Commented Jun 15, 2023 at 3:01
  • It can be more-flexible for elements in the DOM, but if it's not in the DOM (as is the case here) onload is fine. Commented Jun 15, 2023 at 3:32
  • 1
    @holydragon In general, addEventListener is preferable over the on* properties. A possible advantage here is that you don’t have to worry about accidentally overwriting a previous load event handler. The on* properties come from the legacy DOM 0 event model; they are still being added for newer event types, and they can be used for feature detection. However, for regular event binding, addEventListener is where the standardization efforts are currently headed. It’s in a way “more standard”. Commented Jun 15, 2023 at 10:23
7

Easy as this...

var img=new Image();
img.onload=start;
img.src="myImage.png";
function start(){
    ctx.drawImage(img,0,0);
}
2

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

async function drawImage(url, ctx) {
  let img = new Image();
  await new Promise(r => img.onload=r, img.src=url);
  ctx.drawImage(img, 0, 0);
}

let ctx = document.querySelector("#myCanvas").getContext("2d");
await drawImage("https://example.com/image.png", ctx);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.