Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fabric.js: Assigning background color to group

Tags:

I am trying to set a background color for a group without affecting its contained objects.

So far my code looks like this:

var canvas = new fabric.Canvas('canvas');

var helloText = new fabric.Text('hello', {
  fontSize: 30,
  top: 10, left: 10,
  originX: 0, originY: 0
});

var worldText = new fabric.Text('world!', {
  fontSize: 40,
  top: 50, left: 100,
  originX: 0, originY: 0
});

var group = new fabric.Group([helloText, worldText], {
    selectionBackgroundColor: 'red',
    backgroundColor: 'blue'
});

canvas.add(group);

A jsFiddle version can be found here.

As you can see from my code, I already tried the attribute backgroundColor yet it only affects contained objects. I would like to achieve an effect similar to selectionBackgroundColor.

like image 629
Stefan Surkamp Avatar asked Mar 20 '17 16:03

Stefan Surkamp


1 Answers

Slight tweak, but this should do it for you (relevant code):

var text = new fabric.Group([helloText, worldText], {});
var textBoundingRect = text.getBoundingRect();
var background = new fabric.Rect({
  top: textBoundingRect.top,
  left: textBoundingRect.left,
  width: textBoundingRect.width,
  height: textBoundingRect.height,
  fill: 'blue'
});
var group = new fabric.Group([background, text], {});

Your JSFiddle updated, https://jsfiddle.net/rekrah/92ss3d86/.

like image 55
Tim Harker Avatar answered Sep 23 '22 09:09

Tim Harker