Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to crop only the design from a the canvas and ignoring all the white/transparent space?

Tags:

fabricjs

I have a canvas built using fabricJS with the dimension of 600x500. I have added an image to this canvas which is of size 200x300 and also a text element just below it.

$canvasObj.toDataURL(); 

exports the whole canvas area including the white spaces surrounding the design on the canvas.

Is there a way to get the cropped output of the design on the canvas alone instead of all the whitespace?

like image 664
Abishek Avatar asked Sep 20 '25 02:09

Abishek


1 Answers

This can be done by cloning objects to a group, getting the group boundingRect, and then passing the boundingRect parameters to toDataUrl() function (see fiddle).

e.g.

// make a new group
var myGroup = new fabric.Group();
canvas.add(myGroup);

// ensure originX/Y 'center' is being used, as text uses left/top by default.
myGroup.set({ originX: 'center', originY: 'center' });

// put canvas things in new group
var i = canvas.getObjects().length;
while (i--) {
 var objType = canvas.item(i).get('type');
 if (objType==="image" || objType==="text" || objType==="itext" || objType==="rect") {

  var clone = fabric.util.object.clone(canvas.item(i));
  myGroup.addWithUpdate(clone).setCoords();

  // remove original lone object
  canvas.remove(canvas.item(i));
 }
}

canvas.renderAll();

// get bounding rect for new group
var i = canvas.getObjects().length;
while (i--) {
 var objType = canvas.item(i).get('type');
 if (objType==="group") {
  var br = canvas.item(i).getBoundingRect();
 }
}

fabric.log('cropped png dataURL: ', canvas.toDataURL({
    format: 'png',
    left: br.left,
    top: br.top,
    width: br.width,
    height: br.height
}));

p.s. I should probably mention that i've not worked with image types, so i just guessed that it's called 'image'..

like image 54
fzzylogic Avatar answered Sep 23 '25 07:09

fzzylogic