简体   繁体   English

如何将带有图像的画布保存到PNG文件

[英]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 画布和图像的HTML代码

<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 JavaScript代码,用于从服务器获取图像并显示在画布上,然后显示图像

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. 正在显示图像,但没有“ what.jpg”文件。 On the Canvas the file is visiible but in the IMG tag nothing can be seen. 在“画布”上可以看到该文件,但在IMG标签中看不到任何文件。 I am running this on the latest version of Chrome. 我正在最新版本的Chrome上运行它。

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. 您正在加载和绘制jpeg图像之前调用toDataUrl,因此您将获得一个空画布的数据URL。 Move the last three lines of your example into the handler function for image.onload and it should work. 将示例的最后三行移动到image.onload的处理函数中,它应该可以工作。

  2. You are calling .show() on the canvas element, not the img element you assigned the dataUrl to. 您是在canvas元素上调用.show(),而不是为dataUrl分配了img元素。 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. 但是我不知道为什么要这么做,因为看来您的意图是使用不可见的<canvas>为可见的<img>生成内容,这就是CSS样式所说的。

  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. 应该在设置src之前定义onload处理程序,因为当映像位于浏览器缓存中时,可以在设置src属性的那一刻调用onload函数,这是在定义自己的负载处理程序之前。

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

i think the onload call should come before the src. 我认为onload调用应该在src之前。

Like this: 像这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM