Konva – text with block background

Giving text a block color background with margin and padding is catered for well in CSS but not so easy in Konva where there is nothing as capable as CSS built-in. Here’s some code to give you that feature.

TLDR: Here’s the demo CodePen…

I should mention that Konva provides the ‘textBackgroundColor’ attribute, but this no controls for padding. It only fills the space behind the text, which is going to get old quickly when any designers used to margins etc get involved! There is also the built-in ‘padding’ attribute for text. This 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.

The demo code follows the CSS approach where margin is outside of the text-line box, and padding is inside. The padding & margin settings follow the top/right/bottom/left settings as familiar from CSS too, with sliders to see the effect of quick adjustments.

The code is commented for you to enjoy.

Thanks for reading.

VW March 2022.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: