将Fabric js画布另存为PC上的图像
我想通过单击我的html页面中的一个按钮,将织物画布保存为PC上的图像(jpg或png相同)。我尝试了解决方案,但不起作用:
function saveF(canvF) {
var imageCanv = canvF.toDataURL('png');
var myBlob = new Blob(['imageCanv'], { type: "image/png" });
var reader = new FileReader();
reader.onload = function (event) {
var URL = canvF.toDataURL('png');
document.getElementById("lnkDownload").href = URL;
};
reader.readAsDataURL(myBlob);}
这是html标记:
<a class="icon fb" href="" id="lnkDownload" download="canvas.png" style="float:left; background-color:red"><i class="fa fa-save"></i></a>
我建立了其他解决方案,但它们都不起作用
解决方案
这是我的解决方案,下载BLOB(有点像黑客),您可以生成文本文件或其他任何更复杂的文件。
function saveImage(e) {
this.href = canvas.toDataURL({
format: 'jpeg',
quality: 0.8
});
this.download = 'canvas.png'
}
数据-lang="js"数据-隐藏="假"数据-控制台="假"数据-巴贝尔="假">
var canvas = new fabric.Canvas('imageCanvas', {
backgroundColor: 'rgb(240,240,240)'
});
canvas.setWidth(300);
canvas.setHeight(300);
var imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', handleImage, false);
function handleImage(e) {
var objects = canvas.getObjects();
for (var i in objects) {
objects[i].remove();
}
var reader = new FileReader();
reader.onload = function (event) {
var img = new Image();
img.onload = function () {
var imgInstance = new fabric.Image(img, {
selectable: 1
})
canvas.add(imgInstance);
canvas.deactivateAll().renderAll();
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
var imageSaver = document.getElementById('lnkDownload');
imageSaver.addEventListener('click', saveImage, false);
function saveImage(e) {
this.href = canvas.toDataURL({
format: 'png',
quality: 0.8
});
this.download = 'canvas.png'
}
div#container {
padding: 30px;
font-family: 'verdana', lucida;
}
input {
background-color: #ccc;
padding: 0;
width: 300px;
color: #777;
}
a{
color: #777;
display: block;
background-color: #ccc;
width: 300px;
padding: 0;
margin-top: 2px;
text-decoration:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js"></script>
<div id="container">
<input type="file" id="imageLoader" name="imageLoader" />
<canvas id="imageCanvas" width="300" height="300"></canvas>
<a id="lnkDownload" href="#">Save image</a>
</div>
相关文章