使用Javascript将文件扩展名下载Html5 canvas元素作为图像

Nic*_*ray 5 javascript jquery html5 canvas

我希望能够使用Javascript将文件扩展名下载Html5 canvas元素作为图像.

CanvasToImage库似乎并没有能够做到这一点.

到目前为止,这是我的代码,你可以在这个JsFiddle看到.

<div id="canvas_container">
</div>
<p>
<a href='#' id="create_image">create</a> 
<a href="#" id="download_image">download</a>
</p>




$("#create_image").click(function() {
var cnvs = createSmileyOnCanvas();
$('#canvas_container').append(cnvs);
});


$("#download_image").click(function() {    
var img = $('#smiley_canvas').toDataURL("image/png");
var uriContent = "data:application/octet-stream," + encodeURIComponent(img);
window.open(uriContent, 'download smiley image');
});



function createSmileyOnCanvas() {
var canvas = document.createElement('canvas');      
canvas.id = 'smiley_canvas';    
var ctx = canvas.getContext('2d');        

// Draw shapes
ctx.beginPath();
ctx.arc(75,75,50,0,Math.PI*2,true); // Outer circle
ctx.moveTo(110,75);
ctx.arc(75,75,35,0,Math.PI,false);   // Mouth
ctx.moveTo(65,65);
ctx.arc(60,65,5,0,Math.PI*2,true);  // Left eye
ctx.moveTo(95,65);
ctx.arc(90,65,5,0,Math.PI*2,true);  // Right eye
ctx.stroke();

return canvas;
}
Run Code Online (Sandbox Code Playgroud)

小智 10

这似乎对我有用:

<a id="downloadImgLink" onclick="$('#downloadImgLink').attr('href', canvas.toDataURL());" download="MyImage.png" href="#" target="_blank">Download Drawing</a>


Jan*_*nen 2

为了在浏览器的下载对话框中强制/建议文件名,您需要发送标Content-Disposition: attachment; filename=foobar.png头。

这是不可能通过 来完成的window.open,所以你运气不好,除非有一些特定于浏览器的技巧。

a如果您确实需要文件名,您可以尝试使用,中的新下载属性<a href="put stuff here" download="filename here">。但它还没有得到广泛的支持。

另一种选择是首先使用 ajax 将数据提交到服务器,然后将浏览器重定向到某个服务器端脚本,该脚本将使用正确的标头提供数据。