Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save HTML5 canvas with images as an image

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?

like image 500
Jaap Avatar asked Sep 27 '12 11:09

Jaap


People also ask

Can you save HTML canvas as an image?

Saving HTML canvas as an image is pretty easy, it can be done by just right-clicking on the canvas and save it as an image.

How do I convert a canvas object to an image?

function convertCanvasToImage() { let canvas = document. getElementById("canvas"); let image = new Image(); image. src = canvas. toDataURL(); return image; } let pnGImage = convertCanvasToImage(); document.

How do I save an image from HTML?

Open your HTML file in your browser or any viewable tool. Take a snapshot of an area with your screen capture tool (Snipping tool on Windows, for example). Click File > Save as. Select the location and select the Save as type as JPG.


1 Answers

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;
    }
}
like image 52
Dennis Avatar answered Nov 02 '22 23:11

Dennis