简体   繁体   中英

Fabric.js: Resize canvas and continue working

I am working with Fabric.js manipulation images uploaded by users.

Here is how the application works

在此处输入图片说明

The uploaded image can be moved and worked on on the entire canvas (grey area). Once finished, I only need the middle area.

One the user clicks save , currently I save the green area as an image, but I also need to resize the whole canvas to be only the green area.

I tried changing the width and height of the whole canvas and then redrawAll() , but the canvas goes bottom left and only a small portion of the working area is visible, the rest is empty gray.

Is it possible to take a snapshot of the green area and continuing working on the canvas ?

Thank you

You should do extensive use of viewportTransform.

let's make an example: you have a canvas element of 1000x1000 and you want to work on an area of 500x500 pixels.

You set the green area using a green image or a green rect of 500x500 as background image, with top left 0,0. Then you set the viewportTransform of the fabric canvas to [1, 0, 0, 1, 250, 250] this will make your canvas translate to right bottom of that grey border.

When is time to save, you have 2 choices:

1) set a viewportTransform that lets you cover everything of the original canvas and export to dataurl

2) you create an offscreen canvas of 500x500px, you move the objects over there, without touching the new canvas zoom and pan ( viewport transform ) and export that canvas to dataUrl

The snippet has some number for examples, but you need to fully understand how to use and check also the toDataUrl options of fabricCanvas.

 var butt = document.getElementById('butt'); butt.onclick = function() { canvas.viewportTransform = [2, 0, 0, 2, 0, 0]; var img = document.getElementById('export'); img.src = canvas.toDataURL() canvas.viewportTransform = [1, 0, 0, 1, 250, 250]; canvas.renderAll(); } var canvas = new fabric.Canvas('c', { backgroundColor: 'grey' }); var rect = new fabric.Rect({ width: 500, height: 500, fill: 'green'}) canvas.backgroundImage = rect; canvas.viewportTransform = [1, 0, 0, 1, 250, 250]; var exampleRect = new fabric.Rect({left: 5, top: 5, width: 100, height: 100, fill: 'red' }); canvas.add(exampleRect); canvas.renderAll();
 <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.11/fabric.min.js"></script> <img id="export" /> <button id="butt" >export</button> <canvas id="c" width="1000" height="1000"></canvas>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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