Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load image from url and draw to HTML5 Canvas

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);
like image 566
J8m Avatar asked Apr 11 '15 00:04

J8m


3 Answers

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>
like image 88
Alexander O'Mara Avatar answered Nov 03 '22 21:11

Alexander O'Mara


Easy as this...

var img=new Image();
img.onload=start;
img.src="myImage.png";
function start(){
    ctx.drawImage(img,0,0);
}
like image 28
markE Avatar answered Nov 03 '22 20:11

markE


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);
like image 2
joe Avatar answered Nov 03 '22 20:11

joe