Recreate Fabric.js canvas and export as an image?
Fabric has a built in function to convert to data urls. 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. 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>');
Arco_Pelago
Updated on June 23, 2022Comments
-
Arco_Pelago almost 2 years
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. Since the canvas's size iswidth="270"
andheight="519"
, smaller than what the finished product is, I need to recreate it with a canvas that has the sizewidth="1001"
andheight="1920"
and then screenshot it so that I get it all in 1 single image. How do I do this?This is what my code looks like so far:
HTML
<div id="CanvasContainer"> <canvas id="Canvas" width="270" height="519"></canvas> </div>
CSS
#CanvasContainer { width: 270px; height: 519px; margin-left: 15px; } #Canvas { overflow: hidden; }
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); }); });