Save HTML5 canvas with images as image

I try to save the canvas with images in 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 get a blank transparent image without an image. What am I doing wrong?

+4
source share
1 answer

You need to put the window.open call into the load handler, as 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; } } 
+6
source

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


All Articles