如何使用 canvas.toDataURL() 将 Canvas 保存为图像?

2022-01-24 00:00:00 canvas save javascript html cordova

我目前正在构建一个 HTML5 网络应用程序/Phonegap 原生应用程序,但我似乎不知道如何使用 canvas.toDataURL() 将我的画布保存为图像.有人可以帮帮我吗?

I'm currently building a HTML5 web app/Phonegap native app and I can't seem to figure out how to save my canvas as an image with canvas.toDataURL(). Can somebody help me out?

这是代码,有什么问题?

Here's the code, what's wrong with it?

//我的画布被命名为canvasSignature"

//My canvas was named "canvasSignature"

JavaScript:

JavaScript:

function putImage()
{
  var canvas1 = document.getElementById("canvasSignature");        
  if (canvas1.getContext) {
     var ctx = canvas1.getContext("2d");                
     var myImage = canvas1.toDataURL("image/png");      
  }
  var imageElement = document.getElementById("MyPix");  
  imageElement.src = myImage;                           

}  

HTML5:

<div id="createPNGButton">
    <button onclick="putImage()">Save as Image</button>        
</div>

推荐答案

这里有一些代码.没有任何错误.

Here is some code. without any error.

var image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");  // here is the most important part because if you dont replace you will get a DOM 18 exception.


window.location.href=image; // it will save locally

相关文章