Load Image from Url and Draw to HTML5 Canvas

Load image from url and draw to HTML5 Canvas

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>

draw image to canvas in particular order while loading from url to image object

You need to decouple the load listener from drawing. Right now, you are immediately drawing as soon as an image loads. Wrap loading your images in a Promise and use Promise.all(). This will allow you to load all the images in whatever order they can be, but presented back to you in the same order you specified.

/**
* Promisify loading an image
* @param {String} imagePath The web location of the image
* @returns {Promise} A Promise that will resolve to an Image
*/
function loadImage(imagePath) {
return new Promise((resolve, reject) => {
let image = new Image();
image.addEventListener("load", () => {
resolve(image);
});
image.addEventListener("error", (err) => {
reject(err);
});
image.src = imagePath;
});
}

var canvas = document.getElementById("render"),
context = canvas.getContext("2d"),
imageSources = ["image.png", "image.png", "image.png", "image.png"];

Promise
.all(imageSources.map(i => loadImage(i)))
.then((images) => {
images.forEach((image) => {
context.drawImage(image, 0, 0, canvas.width, canvas.height);
});
}).catch((err) => {
console.error(err);
});

Drawing an image from a data URL to a canvas

Given a data URL, you can create an image (either on the page or purely in JS) by setting the src of the image to your data URL. For example:

var img = new Image;
img.src = strDataURI;

The drawImage() method of HTML5 Canvas Context lets you copy all or a portion of an image (or canvas, or video) onto a canvas.

You might use it like so:

var myCanvas = document.getElementById('my_canvas_id');
var ctx = myCanvas.getContext('2d');
var img = new Image;
img.onload = function(){
ctx.drawImage(img,0,0); // Or at whatever offset you like
};
img.src = strDataURI;

Edit: I previously suggested in this space that it might not be necessary to use the onload handler when a data URI is involved. Based on experimental tests from this question, it is not safe to do so. The above sequence—create the image, set the onload to use the new image, and then set the src—is necessary for some browsers to surely use the results.

How to draw image from URL on canvas with original quality

let canvas = document.getElementById('c'),ctx = canvas.getContext('2d');const image = new Image();image.onload = () => {  ctx.imageSmoothingEnabled = false;  ctx.clearRect(0, 0, canvas.width, canvas.height);  ctx.drawImage(image, 50, 50,500,500);};image.src = 'https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.svg?v=6e4af45f4d66';
canvas{ border : 2px solid black;}
<canvas id='c' width=500 height=500/>

How do you deal with html5's canvas image load asynchrony?

Pre-load your images before working with the canvas. Put all your image urls into an array, loop through the array creating new images, and when they are all loaded call a function that will start your canvas work.

Following snippet uses the native JS Promises, but if supporting older browsers that do not have native Promise you can use Q or jQuery libraries in a similar fashion

var images = ['imageurl.jpg','imageurl2.jpg','imageurl3.jpg'];
var loadedImages = {};
var promiseArray = images.map(function(imgurl){
var prom = new Promise(function(resolve,reject){
var img = new Image();
img.onload = function(){
loadedImages[imgurl] = img;
resolve();
};
img.src = imgurl;
});
return prom;
});

Promise.all(promiseArray).then(imagesLoaded);

function imagesLoaded(){
//start canvas work.

//when needing to draw image, access the loaded image in loadedImages
ctx.drawImage(loadedImages['imageurl.jpg'], 300, 100);
}

Cannot Draw Canvas Image On Image's Load

I figured out the issue I was having here. I needed to add width/height attributes to the SVG element I was using as an image.



Related Topics



Leave a reply



Submit