Javascript 如何使用 canvas.toDataURL() 将画布另存为图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10673122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:26:48  来源:igfitidea点击:

How To Save Canvas As An Image With canvas.toDataURL()?

javascripthtmlcordovacanvassave

提问by Wardenclyffe

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?

我目前正在构建一个 HTML5 网络应用程序/Phonegap 本机应用程序,我似乎无法弄清楚如何将我的画布保存为带有canvas.toDataURL(). 有人可以帮我吗?

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

这是代码,有什么问题吗?

//My canvas was named "canvasSignature"

//我的画布被命名为“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:

HTML5:



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

回答by user1874941

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

回答by Thomas W

This solution allows you to change the name of the downloaded file:

此解决方案允许您更改下载文件的名称:

HTML:

HTML:

<a id="link"></a>

JAVASCRIPT:

爪哇脚本:

  var link = document.getElementById('link');
  link.setAttribute('download', 'MintyPaper.png');
  link.setAttribute('href', canvas.toDataURL("image/png").replace("image/png", "image/octet-stream"));
  link.click();

回答by SColvin

You can use canvas2imageto prompt for download.

您可以使用canvas2image来提示下载。

I had the same issue, here's a simple example that both adds the image to the page and forces the browser to download it:

我遇到了同样的问题,这是一个简单的例子,它既将图像添加到页面并强制浏览器下载它:

<html>
    <head>
        <script src="http://hongru.github.io/proj/canvas2image/canvas2image.js"></script>
        <script>
            function draw(){
                var canvas = document.getElementById("thecanvas");
                var ctx = canvas.getContext("2d");
                ctx.fillStyle = "rgba(125, 46, 138, 0.5)";
                ctx.fillRect(25,25,100,100); 
                ctx.fillStyle = "rgba( 0, 146, 38, 0.5)";
                ctx.fillRect(58, 74, 125, 100);
            }

            function to_image(){
                var canvas = document.getElementById("thecanvas");
                document.getElementById("theimage").src = canvas.toDataURL();
                Canvas2Image.saveAsPNG(canvas);
            }
        </script>
    </head>
    <body onload="draw()">
        <canvas width=200 height=200 id="thecanvas"></canvas>
        <div><button onclick="to_image()">Draw to Image</button></div>
        <image id="theimage"></image>
    </body>
</html>

回答by bmatovu

You can try this; create a dummy HTML anchor, and download the image from there like...

你可以试试这个;创建一个虚拟的 HTML 锚点,然后从那里下载图像,例如...

// Convert canvas to image
document.getElementById('btn-download').addEventListener("click", function(e) {
    var canvas = document.querySelector('#my-canvas');

    var dataURL = canvas.toDataURL("image/jpeg", 1.0);

    downloadImage(dataURL, 'my-canvas.jpeg');
});

// Save | Download image
function downloadImage(data, filename = 'untitled.jpeg') {
    var a = document.createElement('a');
    a.href = data;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
}

Here is the fiddle

这是小提琴

回答by gillyb

I created a small library that does this (along with some other handy conversions). It's called reimg, and it's really simple to use.

我创建了一个小型库来执行此操作(以及其他一些方便的转换)。它叫做reimg,使用起来非常简单。

ReImg.fromCanvas(yourCanvasElement).toPng()

ReImg.fromCanvas(yourCanvasElement).toPng()

回答by 1000Bugy

This work for me: (Only google chrome)

这对我有用:(仅谷歌浏览器)

<html>
<head>
    <script>
            function draw(){
                var canvas = document.getElementById("thecanvas");
                var ctx = canvas.getContext("2d");
                ctx.fillStyle = "rgba(125, 46, 138, 0.5)";
                ctx.fillRect(25,25,100,100);
                ctx.fillStyle = "rgba( 0, 146, 38, 0.5)";
                ctx.fillRect(58, 74, 125, 100);
            }

            function downloadImage()
            {
                var canvas = document.getElementById("thecanvas");
                var image = canvas.toDataURL();

                var aLink = document.createElement('a');
                var evt = document.createEvent("HTMLEvents");
                evt.initEvent("click");
                aLink.download = 'image.png';
                aLink.href = image;
                aLink.dispatchEvent(evt);
            }
    </script>
</head>
<body onload="draw()">
    <canvas width=200 height=200 id="thecanvas"></canvas>
    <div><button onclick="downloadImage()">Download</button></div>
    <image id="theimage"></image>
</body>
</html>

回答by Sjeiti

Similar to 1000Bugy's answerbut simpler because you don't have to make an anchor on the fly and dispatch a click event manually (plus an IE fix).

类似于1000Bugy 的答案,但更简单,因为您不必即时制作锚点并手动调度点击事件(加上 IE 修复)。

If you make your download button an anchor you can highHyman it right before the default anchor functionality is run. So onAnchorClickyou can set the anchor href to the canvas base64 image and the anchor download attribute to whatever you want to name your image.

如果您将下载按钮设置为锚点,则可以在运行默认锚点功能之前对其进行劫持。因此,onAnchorClick您可以将锚点 href 设置为画布 base64 图像,并将锚点下载属性设置为您想要为图像命名的任何内容。

This does not work in (the current) IE because it doesn't implement the download attribute and prevents download of data uris. But this can be fixed by using window.navigator.msSaveBlobinstead.

这在(当前)IE 中不起作用,因为它没有实现下载属性并阻止下载数据 uri。但这可以通过使用window.navigator.msSaveBlob来解决。

So your anchor click event handler would be as followed (where anchor, canvasand fileNameare scope lookups):

因此,您的锚点单击事件处理程序将如下所示(其中anchorcanvasfileName是范围查找):

function onClickAnchor(e) {
  if (window.navigator.msSaveBlob) {
    window.navigator.msSaveBlob(canvas.msToBlob(), fileName);
    e.preventDefault();
  } else {
    anchor.setAttribute('download', fileName);
    anchor.setAttribute('href', canvas.toDataURL());
  }
}

Here's a fiddle

这是一把小提琴

回答by Hakan Serce

Instead of imageElement.src = myImage;you should use window.location = myImage;

而不是imageElement.src = myImage;你应该使用window.location = myImage;

And even after that the browser will display the image itself. You can right click and use "Save Link" for downloading the image.

即使在那之后,浏览器也会显示图像本身。您可以右键单击并使用“保存链接”来下载图像。

Check this linkfor more information.

查看此链接以获取更多信息。

回答by Vinay Chandra

@Wardenclyffe and @SColvin, you both are trying to save image using the canvas, not by using canvas's context. both you should try to ctx.toDataURL(); Try This:

@Wardenclyffe 和@SColvin,你们都在尝试使用画布保存图像,而不是使用画布的上下文。你应该尝试 ctx.toDataURL(); 尝试这个:

var canvas1 = document.getElementById("yourCanvasId");  <br>
var ctx = canvas1.getContext("2d");<br>
var img = new Image();<br>
img.src = ctx.toDataURL('image/png');<br>
ctx.drawImage(img,200,150);<br>

Also you may refer to following links:

您也可以参考以下链接:

http://tutorials.jenkov.com/html5-canvas/todataurl.html

http://tutorials.jenkov.com/html5-canvas/todataurl.html

http://www.w3.org/TR/2012/WD-html5-author-20120329/the-canvas-element.html#the-canvas-element

http://www.w3.org/TR/2012/WD-html5-author-20120329/the-canvas-element.html#the-canvas-element