Rahul Kadukar
Rahul Kadukar

Reputation: 958

How to save a canvas with image to a PNG file

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.

Upvotes: 1

Views: 17288

Answers (2)

Philipp
Philipp

Reputation: 69663

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';

Upvotes: 8

Xavero
Xavero

Reputation: 3389

i think the onload call should come before the src.

Like this:

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

Upvotes: 0

Related Questions