Konva – handy trick to apply opacity to rect fill but leave stroke unchanged

Ever needed to have a rect with alpha applied to the fill bit not the stroke – here’s how.

TLDR: See the demo here.

Say you wanted to do what you can see in the left hand rect in the image above – the fill has alpha transparency applied but the stroke does not. Normally we define a rect with opacity as:

const settings = {
    stroke: 'red',
    fill: 'lime',
    opacity: 0.5
    }
const rect = New Konva.rect(stroke: settings.stroke, fill: settings.fill, opacity: settings.opacity})

That will make a rect then apply the opacity to the entire shape. What if you wanted to keep the stroke fully opaque (no transparency) and you only want the fill to look faded?

const settings = {
    stroke: 'red',
    fill: 'lime',
    opacity: 0.5
    }

// check if the fill is transparent and set opacity accordingly
settings.opacity = (settings.fill === 'transparent') ? 0 : settings.opacity;

// Use Konva.Util to get the color parts
const colorParts = Konva.Util.getRGB(settings.fill);
function getHex(val){
      return (val.toString(16).length < 2)?'0'+ val.toString(16) : val.toString(16);
}
settings.fill = '#' + getHex(colorParts.r) + getHex(colorParts.g) +  getHex(colorParts.b) + getHex(Math.floor(255 * opacity));

// Notice - no opacity property is set here now !!
const rect = New Konva.rect(stroke: settings.stroke, fill: settings.fill})

The magic here is the use of the Konva.Utils.getRGB() method which returns an object with r, g and b properties giving the red, green and blue colour values in the range 0 – 255. We need to convert that to hex which is what the getHex() function does, with the added feature of ensuring we get a 2 digit value so that for example 0 is returned as ’00’.

After that we need to turn the opacity value which is a fraction between 0 – 1 into a value between 0 and 255, which is done with Math.floor(255 * opacity).

Et voila – we now have an RGBA colour for the fill, including opacity setting, but the stroke remains fully opaque (not transparent).

Thanks for reading.

VW April 22.

One thought on “Konva – handy trick to apply opacity to rect fill but leave stroke unchanged

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: