Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
188
rated 0 times [  195] [ 7]  / answers: 1 / hits: 17147  / 11 Years ago, thu, april 4, 2013, 12:00:00

I am using the following code



HTML Code for the Canvas and the image



<canvas id=myCanvas style=display:none width=400 height=400></canvas>
<img id=canvasImg />


JavaScript code for fetching the image from the server and displaying on the canvas followed by displaying the image



var canvas = document.getElementById(myCanvas);
var ctx = canvas.getContext(2d);

baseimage = new Image();
baseimage.src = 'what.jpg';
baseimage.onload = function() {
ctx.drawImage(baseimage,1,1);
}

var dataURL = canvas.toDataURL(image/png);
document.getElementById('canvasImg').src = dataURL;
$(#myCanvas).show();


The image is being displayed but without the what.jpg file. On the Canvas the file is visiible but in the IMG tag nothing can be seen. I am running this on the latest version of Chrome.


More From » jquery

 Answers
4

There are several problems with your code.




  1. You are calling toDataUrl before the jpeg image has been loaded and drawn, so you get the data URL of an empty canvas. Move the last three lines of your example into the handler function for image.onload and it should work.


  2. You are calling .show() on the canvas element, not the img element you assigned the dataUrl to. But I wonder why you do this at all, because it seems like your intention is to use an invisible <canvas> to generate content for a visible <img>, and that's what the CSS styling says.


  3. The onload handler should be defined before setting the src, because when the image is in the browsers cache, the onload function could be called the moment the src attribute is set, which is before you defined your own load handler.




This is the fixed code (untested):



var canvas = document.getElementById(myCanvas);
var ctx = canvas.getContext(2d);

baseimage = new Image();
baseimage.onload = function() {
ctx.drawImage(baseimage,1,1);
var dataURL = canvas.toDataURL(image/png);
document.getElementById('canvasImg').src = dataURL;
}
baseimage.src = 'what.jpg';

[#79122] Wednesday, April 3, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
juancarlos

Total Points: 580
Total Questions: 105
Total Answers: 103

Location: Grenada
Member since Sun, Dec 20, 2020
3 Years ago
;