So now we have our cool header with a custom paint background, let's expand on it.
We'll update the paint()
function to draw a more funky background and wouldn't it be great if we could choose the colour of the background whenever we wanted to use it? Another feature of the Paint API is the ability to access custom properties available to the element.
Let's take a look:
My Cool Header
My Cool Header
We add a custom property in our CSS:
.example {
--highColour: hsla(55, 90%, 60%, 1.0);
background-image: paint(headerHighlight);
}
Now we can use the inputProperties()
method in the registerPaint()
class, grab that property and use it within our paint()
function:
static get inputProperties() { return ['--highColour']; }
Note: The inputProperties()
method returns all properties affecting the element, not just custom properties.
paint(ctx, size, props) {
// Paint uses Typed OM to retrieve the custom property value, so, as with the Typed OM API, we have to use the get()
method to access the value
ctx.fillStyle = props.get('--highColour');
...
}
Back in our CSS, on elements that have this paint()
function generating their backgound, we can reset the --highColour
custom property to change its color:
.example {
--highColour: hsla(55, 90%, 60%, 1.0);
background-image: paint(headerHighlight);
}
.example:nth-of-type(2) {
--highColour: hsla(155, 90%, 60%, 1.0);
}
You can check out the entire registerPaint()
function in header-highlight.js here. Not only can we pass in custom properties, but also custom arguments when we call the paint()
function in our css. Let's take a look in part 4.