I am using the library FabricJS to overlay text on canvas. I need to add padding (ideally just left & right) to a text element that includes the property textBackgroundColor.
Here is what I've tried so far:
let textObject = new fabric.Text('Black & White',{
fontFamily: this.theme.font,
fontSize: this.theme.size,
textBaseline: 'bottom',
textBackgroundColor: '#000000',
left: 0,
top: 0,
width: 100,
height: 40,
padding: 20,
fill: 'white',
});
The padding doesn't work as I anticipated. I have attempted to use the backgroundColor property but that adds background to the whole group block and not just the text.
I could add a a non-breaking space to achieve the same effect, but this doesn't seem like a reliable solution and I was hoping Fabric JS allowed this out-of-the-box. Any ideas how to achieve this?
Required solution (version on the right, with additional padding is what I would like):
I give you 2 answers for two subtly different cases.
Case 1 - padding around the bounding box of single of multi-line text. The code follows the CSS approach where margin is outside of the box, as depicted by the red line, and padding is inside, as shown by the gold background. On the left hand image, black text background is what you get from the built-in 'textBackgroundColor'. The yellow area shows the padding currently applied. The right hand image shows the additional benefit when you harmonise the padding colour, an also that you can reduce opacity on the background whilst keeping the text full-opaque.
BTW the built-in 'padding' attribute for text pads in relation to the controlling border, but the background color fill does not cover the white-space created. In other words, it operates like CSS margin rather than CSS padding.
Therefore it is necessary to ignore this padding attribute, and instead introduce a coloured rect to give the background color required, grouping this with the text element and positioning accordingly.
Example snippet below.
Case 2: padding boxing the individual text lines and not the full bounding box.
In this case you can see the difference in how the padded background tracks each line of text instead of applying to the outer bounding box of the text. The solution is more complex, involving creating a dummy text node which then provides line splitting and sizing information. We then loop thru the line data, outputting individual text lines and padding rects into a group which means we can position and handle the text as a single object, as illustrated by the applied angle.