6

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.

1 Answer 1

4

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/.

2
  • 1
    Your tweak was my fallback solution ;) Yet, I didn't consider using the bounding rect size to define the background rect's size. Thanks! Commented Mar 22, 2017 at 14:56
  • Yep. I find some of the keywords a little misleading when it comes to FabricJS, I guess you could go both ways with whether backgroundColor should refer to the group or to the individual items in the group, I guess. But I do think that whichever way you go, selectionBackgroundColor should be consistent - so since backgroundColor refers to individual items in the group, so should selectionBackgroundColor - or visa versa. If you get my drift? Happy to have helped, matey!
    – Tim Harker
    Commented Mar 22, 2017 at 15:13

Not the answer you're looking for? Browse other questions tagged or ask your own question.