Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
550 views
in Technique[技术] by (71.8m points)

javascript - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...