简体   繁体   English

重新创建Fabric.js画布并导出为图像?

[英]Recreate Fabric.js canvas and export as an image?

I have a canvas where the user can create a design using images in another div that they click, sending it to the Fabric.js canvas where it gets moved around and so on. 我有一个画布,用户可以使用他们点击的另一个div中的图像创建设计,将其发送到Fabric.js画布,在那里它可以移动,依此类推。 Since the canvas's size is width="270" and height="519" , smaller than what the finished product is, I need to recreate it with a canvas that has the size width="1001" and height="1920" and then screenshot it so that I get it all in 1 single image. 由于画布的尺寸是width="270"height="519" ,小于成品,我需要用尺寸width="1001"height="1920"的画布重新创建它截图,以便我在1张单张图片中获取所有内容。 How do I do this? 我该怎么做呢?

This is what my code looks like so far: 这是我的代码到目前为止的样子:

HTML HTML

<div id="CanvasContainer">
    <canvas id="Canvas" width="270" height="519"></canvas>
</div>

CSS CSS

#CanvasContainer {
    width: 270px;
    height: 519px;
    margin-left: 15px;
}
#Canvas {
    overflow: hidden;
}

JAVASCRIPT JAVASCRIPT

//Defining Canvas and object array
var canvas = new fabric.Canvas('Canvas');

//When clicked
$(document).ready(function () {
    $("#Backgrounds img").click(function () {
        var getId = $(this).attr("id");

        //adding all clicked images
        var imgElement = document.getElementById(getId);
        var imgInstance = new fabric.Image(imgElement, {
            left: 135,
            top: 259,
            width: 270,
            height: 519
        });
        //Corner color for clicked images
        imgInstance.set({
            borderColor: 'white',
            cornerColor: 'black',
            transparentCorners: false,
            cornerSize: 12
        });
        canvas.add(imgInstance);
    });
});

Fabric has a built in function to convert to data urls. Fabric具有内置函数以转换为数据URL。 You can use the download property of a link to make the link a download link. 您可以使用链接的下载属性将链接设为下载链接。 Finally you can use the DOM click() function to emulate clicking the download link. 最后,您可以使用DOM click()函数来模拟单击下载链接。 The end result is: 最终结果是:

function download(url,name){
// make the link. set the href and download. emulate dom click
  $('<a>').attr({href:url,download:name})[0].click();
}
function downloadFabric(canvas,name){
//  convert the canvas to a data url and download it.
  download(canvas.toDataURL(),name+'.png');
}

now when you want to download the canvas call 现在当你想下载画布调用时

downloadFabric(canvas,'<file name>');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM