It would be better if we had an idea of the size of our element, so we could create the background relative to the element; this way we could use the same background on other elements as well, and the background would always fit.
The second parameter we can pass into the paint()
function gives us access to the width and the height of the element, via .width
and .height
properties. Pretty handy.
Let's take a look at our header-highlight.js
script now we can use this functionality.
registerPaint('headerHighlight', class {
// Whether Alpha is allowed - This is set to true by default, if it is set to false all colours used on the canvas will have full opacity, or alpha of 1.0
static get contextOptions() { return {alpha: true}; }
paint(ctx, size) {
// ctx - drawing context
// size - size of the box being painted
ctx.fillStyle = 'hsla(55, 90%, 60%, 1.0)';
ctx.fillRect(0, size.height/4, size.width*0.66, size.height*0.7);
}
});
Our header now has a highlight which changes according to it's size.
My Cool Header
And there's more, we can start to access custom properties inside our worklet function as well. Go to Part Three