Why can't I use the javascript function to draw more than one image on an html canvas?

I have a javascript function like:

function drawImage(canvas, image_source, dx, dy) { image = new Image(); image.src = image_source; image.onload = function() { c=canvas.getContext("2d"); c.drawImage(image,dx,dy,100,100); } } 

When I call this function twice in a row, for example:

 drawImage(canvas, "foo.jpg", 0, 0); drawImage(canvas, "bar.jpg", 0 ,100); 

The bar is painted twice, once at 0 and once every 100 seconds. If I switch the order so that foo is called last, foo will be painted twice.

I tried using an array for images, as in "c.drawImage (images [loaded ++], dx, dy, 100, 100", and the two images color separately, but their orders are random.

Can this function be used to draw images on canvas?

+4
source share
1 answer

Try changing:

 image = new Image(); 

in

 var image = new Image(); 

You are currently installing the “image” in the global scope, and then perhaps rewriting the onload handler before the download (which does not happen synchronously).

+7
source

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


All Articles