5

I'm trying to save a canvas with images to PNG, but when I try this:

var myCanvas = document.getElementById("myCanvas"); var img = document.createElement('img'); var ctx = myCanvas.getContext ? myCanvas.getContext('2d') : null; img.src = 'image.png'; img.onload = function () { ctx.drawImage(img, 0, 0, myCanvas.width, myCanvas.height); } var data = myCanvas.toDataURL("image/png"); if (!window.open(data)) { document.location.href = data; } 

I only get a blank transparent image without the image. What am I doing wrong?

1 Answer 1

6

You need to put the window.open call in the load handler since this happens asynchronously.

img.onload = function () { ctx.drawImage(img, 0, 0, myCanvas.width, myCanvas.height); var data = myCanvas.toDataURL("image/png"); if (!window.open(data)) { document.location.href = data; } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.