How to import/use library in Paint Worklet?

685 views Asked by At

I'm trying to check if it's possible to use canvas library inside Paint Worklet. I've tried to test if I can use paper.js. The problem is that I can't load the library in worklet, global script that don't give access to the library and importScripts from web woker don't work.

Is it possible to use libraries inside paint Worklet?

It seems that the only thing I need to use paper.js with PaintAPI is to mock CanvasProvider object that return paint worklet context instead of canvas.getContext('2D');. The problem is that I can use self like in worker and I don't have access to paper object.

I have code like this:

CSS.paintWorklet.addModule(blobify(function() {
    //importScripts('https://cdn.statically.io/gh/paperjs/paper.js/prebuilt/module/dist/paper-full.js');

    class Circle {

        static get inputProperties() {
            return ['--pointer-x', '--pointer-y', '--pointer-options'];
        }

        paint(context, geom, properties) {
            /*
            self.CanvasProvider = {
                getContext: function() {
                    return context;
                }
            };
            console.log(paper);
            */
            var x = properties.get('--pointer-x').value || 0;
            var y = properties.get('--pointer-y').value || 0;
            const prop = properties.get('--pointer-options');
            const {
                background,
                color,
                width
            } = Object.assign({
                color: 'white',
                background: 'black',
                width: 10
            }, JSON.parse(prop.toString()));
            context.fillStyle = color;
            //console.log({x,y, color, background, width})
            context.beginPath();
            context.arc(x, y, Math.floor(width / 2), 0, 2 * Math.PI, false);
            context.closePath();
            context.fill();
        }
    }
    registerPaint('circle', Circle);
}));

not working code is commented out, you can try to play with this on CodePen.

2

There are 2 answers

1
Kaiido On

Worklets are all module scripts, so you can simply import your library from your script.

const lib_url = blobifyScript(`
const foo_obj = { foo: "bar" };
export default foo_obj;
`)

const worklet_url = blobifyScript(`
import foo_obj from "${lib_url}";
console.log( foo_obj.foo );
`);

CSS.paintWorklet.addModule( worklet_url )
  .then( () => console.log( "check your browser's console" ) )
  .catch( console.error );

function blobifyScript( content ) {
  return URL.createObjectURL( new Blob ( [ content ], { type: 'application/javascript' } ) )
};

0
jcubic On

It seems that there is one paintWorklet in browser so you can run:

CSS.paintWorklet.addModule('library');
CSS.paintWorklet.addModule('my code');

and my code will share the library code, other issue is that paper.js don't work because of browser dependency.