Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
157
rated 0 times [  161] [ 4]  / answers: 1 / hits: 15103  / 12 Years ago, mon, april 23, 2012, 12:00:00

I am attempting to draw a dynamic PNG image (one that is generated by a PHP script) onto a Canvas element using its URL. I can't really post exact URLs for pages I'm testing this out on, as you must be logged in to the website.



An example of one of the dynamic image URL I'm using is: http://www.website.com/includes/dynamicimage.php?ID=29718958161



If you were logged into this particular website and pasted that URL into your address bar, it would correctly display the image. However, the following Javascript code is not properly drawing it onto 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'm having two pop-up windows display both the dynamic image and what is drawn to the canvas, but the canvas is always blank. I am then attempting to do further RGB testing on the image after setting the pix variable, but since the image is never drawn to the canvas element, this step fails.


More From » image

 Answers
94

Your problem is that you are not waiting for the image to load before attempting to draw it to the canvas. See the section titled Playing It Safe in this question for more details.



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.

[#86046] Sunday, April 22, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
destiniemartinac

Total Points: 92
Total Questions: 106
Total Answers: 111

Location: Cyprus
Member since Mon, Oct 24, 2022
2 Years ago
;