Download the image from the URL and draw on the HTML5 canvas.

I am having trouble loading an image from a URL in javascript. The code below works, but I do not want the image to be loaded from html. I want to download an 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); 
+6
source share
2 answers

Simple, just create an image object in JavaScript, set src and wait for the event to load 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> 
+18
source

Easy as it is ...

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

Source: https://habr.com/ru/post/984971/


All Articles