Recover Canvas Fabric.js and export as 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 moves, etc. Since the canvas size width="270" and height="519" is smaller than the finished product, I need to recreate it with a canvas of width="1001" and height="1920" size, and then take it off so that I get all in 1 single image. How to do it?

This is what my code looks like:

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); }); }); 
+6
source share
1 answer

The fabric has a built-in function to convert to data URLs. You can use the link download property so that the link is a download link. Finally, you can use the DOM click() function to emulate a click on a download link. Final result:

 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 that you want to load the canvas call

 downloadFabric(canvas,'<file name>'); 
+9
source

Source: https://habr.com/ru/post/958261/


All Articles