CarinaPilar
CarinaPilar

Reputation: 1084

Why HTML 5 Canvas Does Not Draw Image Content?

I'm trying to generate an image from a HTML 5 Canvas, but it's not "rendering" image content from the canvas.

Here is the code: http://jsfiddle.net/9kQPk/

It's supposed to be simple, I create a canvas, set a few things and a image using "drawImage" function, but when I try to generate an img html component, the image from canvas does not appear... Here is the JS:

$('#drawing').css("visibility", "visible");         
var drawing = document.getElementById("drawing");
var con = drawing.getContext("2d");         
drawing.setAttribute("width", 500);
drawing.setAttribute("height", 200);
con.fillStyle = "#FF0000";
con.fillRect(0, 0, 500, 200);                                           
var img = new Image();
img.src = "http://www.deque.com/wbcntnt928/wp-content/dquploads/jquery_logo.png";
img.onload = function() {                
    con.drawImage(img, 0, 0, 250, 250);
};

//Generate Image
var drawing = document.getElementById("drawing");
var dataURL = drawing.toDataURL();
document.getElementById("result").src = dataURL;

Thanks!

Upvotes: 0

Views: 1906

Answers (1)

Musa
Musa

Reputation: 97717

You're getting content of the canvas before you draw the image, put the generate image code in the onload function

var img = new Image();
img.onload = function() {                
    con.drawImage(img, 0, 0, 250, 250);
    //Generate Image
    var drawing = document.getElementById("drawing");
    var dataURL = drawing.toDataURL();
    document.getElementById("result").src = dataURL;
};
img.src = "http://www.deque.com/wbcntnt928/wp-content/dquploads/jquery_logo.png";

note that the image must be of the same origin as the webpage drawing it to be able to save it.

DEMO
Code

Upvotes: 1

Related Questions