Search code examples
electronpaperjs

Getting paperjs to work in an electron app


Another learning project in the works... I am trying to use paperjs in an electron app. According to the instructions, I think I should be using paper-jsdom (please correct me if I'm wrong). BTW, I am using TypeScript if that makes a difference. I have an HTML document with nothing but an empty <canvas> and a <script> tag referencing this:

import paper, {Color, Point, Path} from 'paper-jsdom'

window.onload = (): void => {
    let canvas = document.getElementById("workspace") as HTMLCanvasElement;
    paper.setup(canvas);

    let path = new Path();
    path.strokeColor = Color.random();
    let start = new Point(100, 100);
    path.moveTo(start);
    path.lineTo(start.add(new Point(200, -50)));
    paper.view.update();
};

So right off the bat I get:

Uncaught TypeError: paper_jsdom_1.Path is not a constructor

Ugh... So I tried a few random things (it's late, I'm tired...) and changing my import to:

import paper from 'paper'
import {Color, Point, Path} from 'paper-jsdom'

works, or at least the code above works.

Am I supposed to be importing some things from 'paper' and others from 'paper-jsdom'? What is the correct way to use paperjs in an electron app?

Unfortunately paper-jsdom doesn't seem to have any type info for TS.

Thanks!!


Solution

  • Since you are using Paper.js in the renderer process of Electron, you are using it in the browser context and not in Node.js context so you should use the common paper package which relies on browser Canvas API (and not paper-jsdom which targets browserless usage).
    So you should be able to use Paper.js as you would for a website.

    From your code example, I see that you are using TypeScript so you can have a look at this simple quickstart project that I made to play with Paper.js and TypeScript.
    It uses this kind of import:

    import * as paper from 'paper';
    

    And then access Paper.js classes through the imported paper object:

    new paper.Path.Circle({
        center   : paper.view.center,
        radius   : 50,
        fillColor: 'orange',
    });
    

    Edit

    Here is a repository showing the simplest way of using Paper.js in an Electron app.