如何将图片的画布保存为PNG文件

如何将图片的画布保存为PNG文件

本文介绍了如何将图片的画布保存为PNG文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码

HTML 代码用于画布和图片

<canvas id="myCanvas" style="display:none" width="400" height="400"></canvas>
<img id="canvasImg" />

JavaScript 代码,用于从服务器获取图片并在画布上显示然后显示图像

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();

正在显示图片,但没有what.jpg文件。在画布上的文件是可见的,但在IMG标签没有什么可以看到。

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.

推荐答案

您的代码有几个问题。


  1. 在加载和绘制jpeg图像之前,您调用了dataUrl,因此您获取了一个空画布的数据网址。

  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.

你在canvas元素上调用.show() ,而不是您分配dataUrl的img元素。但是我想知道为什么你这样做,因为它似乎是你的意图是使用隐形< canvas> 生成内容的可见

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.

onload处理程序应该在设置src之前定义,因为当图像在浏览器缓存中时,onload函数可以在设置src属性的时刻被调用,这是在您定义自己的加载处理程序之前。

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

这篇关于如何将图片的画布保存为PNG文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 13:56