Javascript draws a dynamic image from a URL onto a canvas element

I am trying to draw a dynamic PNG image (the one generated by a PHP script) on a Canvas element using its URL. I can’t post the exact URLs for the pages on which I am testing this, since you have to log in to the website.

An example of one of the dynamic image URL that I use: http://www.website.com/includes/dynamicimage.php?ID=29718958161

If you logged into this particular website and pasted that URL into your address bar, it would display the image correctly. However, the following Javascript code incorrectly draws it on the canvas element:

function checkImage(imageContext) { var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas'); canvas.width = imageContext.width; canvas.height = imageContext.height; var context = canvas.getContext("2d"); var img = new Image(); img.src = imageContext.src; context.drawImage(img, 0, 0); newWindow = window.open(imageContext.src, 'newWin', 'width=300,height=300'); newWindow2 = window.open('', 'newWin2', 'width=300,height=300'); newWindow2.document.body.appendChild(canvas); var imgd = context.getImageData(0, 0, imageContext.width, imageContext.height); var pix = imgd.data; } 

I have two pop-ups displaying both a dynamic image and what is drawn on the canvas, but the canvas is always empty. Then I try to do further RGB tests on the image after setting the "pix" variable, but since the image is never drawn on the canvas element, this step is not performed.

+6
source share
1 answer

Your problem is that you do not wait for the image to load before you try to draw it on the canvas. For more information, see the section titled “Playback safe” on this subject .

In short:

 var img = new Image; // First create the image... img.onload = function(){ // ...then set the onload handler... ctx.drawImage(img,0,0); }; img.src = "someurl"; // *then* set the .src and start it loading. 
+13
source

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


All Articles