javascript 将画布另存为 PNG 或 JPG
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11206955/
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
Saving canvas as a PNG or JPG
提问by UXX1
I want to save canvas as PNG, without opening it in a new window as base64-encoded image.
我想将画布保存为 PNG,而不是在新窗口中将其作为 base64 编码图像打开。
I used this code:
我使用了这个代码:
jQuery("#btnPreview").click(function(){
if (!fabric.Canvas.supports('toDataURL')) {
alert('Sorry, your browser is not supported.');
}
else {
canvas.deactivateAll();
canvas.forEachObject(function(o){
if(o.get("title") == "||Watermark||"){
canvas.bringToFront(o);
}
});
window.open(canvas.toDataURL('png'), "");
canvas.forEachObject(function(o){
if(o.get("title") == "||Watermark||"){
canvas.sendToBack(o);
}
});
canvas.renderAll();
}
});
I want to make the button save the image as a PNG or JPG.
我想让按钮将图像保存为 PNG 或 JPG。
回答by Dakshika
I use this on my jquery:
我在我的 jquery 上使用这个:
var image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
$('.save').attr({
'download': 'YourProduct.png', /// set filename
'href' : image /// set data-uri
});
回答by rodneyrehm
canvas.toDataURL('png')
provides a string a la data:image/png;base64,XYZ
. You could stuff that into an <a href="%dataURI%" download>download</a>
(possibly trigger a click event on the element). See Downloading resources in HTML5: a[download]
canvas.toDataURL('png')
提供一个字符串 a la data:image/png;base64,XYZ
。你可以把它塞进一个<a href="%dataURI%" download>download</a>
(可能触发元素上的点击事件)。参见下载 HTML5 资源:a[下载]
Currently supported only by Google Chrome, though.
不过,目前仅受 Google Chrome 支持。
回答by saad
In script.js file
在 script.js 文件中
$(document).on('click','#btnPreview',function(){
var img =$scope.canvas.toDataURL('image/png');
$.ajax({
type: "POST",
url: 'ajax.php',
data: {'img':img},
success: function(data) {
$("#loader_message").html("Image saved successfully");
}
});
});
In ajax.php
在 ajax.php 中
$encodedData=explode(',', $_POST["img"]);
$data = base64_decode($encodedData[1]);
$urlUploadImages = $_SERVER['DOCUMENT_ROOT'].$projName.'/images/canvas/';
$nameImage = "test.png";
$img = imagecreatefromstring($data);
if($img) {
imagepng($img, $urlUploadImages.$nameImage, 0);
imagedestroy($img);
echo "OK";
}
else {
echo 'ERROR';
}