cssreactjspainthoudini

How to use CSS Paint API with React


I'm trying to set the most basic example of React with the CSS Paint API.

I have no compiling errors and yet the example doesn't show.

Inside index.html:

<script>
CSS.paintWorklet.addModule('%PUBLIC_URL%/paintWorklet.js');
</script>

public/paintWorklet.js:

class Shape {
  paint(ctx, geom, properties) {
    ctx.strokeStyle = 'red';
    ctx.lineWidth = 4;
    ctx.beginPath();
    ctx.arc(200, 200, 50, 0, 2 * Math.PI);
    ctx.stroke();
    ctx.closePath();
  }
}

registerPaint('pattern', Shape);

App.tsx:

import React from 'react';
import './App.css';

const TestDiv = () => {  
  return(
    <div className='TestDiv'>
      <h1>I am a TestDiv</h1>
    </div>
  )
}

function App() {
  return (
    <div className="App">
      <TestDiv />
    </div>
  );
}

export default App;

App.css:

.TestDiv {
  background: paint(pattern);
}

So far I have tried to move the worklet inside src, having it inside a useEffect and still no luck.

Although this snippet inside index.html works.

 <style>
  body {
    margin: 0;
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    background: paint(pattern);
  }
</style>

Solution

  • I found the issue is:

    Solutions:

    enter image description here

    See demo