I have a React/Electron app, where I'm trying to use the new CSS Houdini paint()
function (as demonstrated in this page). In my project's index.html
file I have added a script tag with the paintWorklet addModule()
function as shown:
<script>
CSS.paintWorklet.addModule('../src/ResultDisplay/DefaultResultDisplay/testPaint.js');
</script>
Then in that testPaint.js
file I have essentially a copy of what's shown in that blog post:
registerPaint(
"testPaint",
class {
paint(ctx, geom) {
console.log("painting!!!");
const circleSize = 10;
const bodyWidth = geom.width;
const bodyHeight = geom.height;
const maxX = Math.floor(bodyWidth / circleSize);
const maxY = Math.floor(bodyHeight / circleSize);
for (let y = 0; y < maxY; y++) {
for (let x = 0; x < maxX; x++) {
ctx.fillStyle = "blue";
ctx.beginPath();
ctx.arc(
x * circleSize * 2 + circleSize,
y * circleSize * 2 + circleSize,
circleSize,
0,
2 * Math.PI,
true
);
ctx.closePath();
ctx.fill();
}
}
}
}
);
And finally my css file:
.container {
background-image: paint(testPaint);
display: flex;
margin: 4px;
border-radius: 12px;
height: 75px;
}
I should point out I am using CSS Modules, so this file is defaultResultStyles.module.scss
; not sure if that affects anything. When I bring up the component that's meant to have these styles in my app, it has no styles, though inspecting it, it does display background-image: paint(testPaint). The console.log that I added to the
testPaint.js` file is never shown.
I have tried multiple variations of the filepath for addModule
; I've tried just testPaint.js
, starting it with ./src
and src
both, but nothing seems to work; is this possible in an Electron/React app?
The addModule function will not work through webpack or other bundlers, it instead works through the native module system of browsers. You have to put the
testPaint.js
file in the public directory, otherwise it would get bundled with everything else.Here's what I added to the index.html to get it to run from the public directory on a local Create React App project:
I didn't actuallly set up any of the markup and just added the container class to test it out:
If you want to use this without going through the public folder (at all, because normally you'd have to add the paint module in the index.html which is changing the public directory), then I'd suggest using React Helmet to set up the script tags. As a note with this, the hot-reload features of CRA seems to prevent the scripts from updating, so every time you change the script tags, you'll need to refresh the page manually.