Calling a PaperScript function from JavaScript

<> Posted on June 2, 2015 in Code

I've just uploaded an online color gamut visualizer to the WheelMasks blog. It's something I thought about adding to the app but chose not to, to avoid adding complexity.

There are already a number of gamut visualizers available, but none of the ones I know of have any visual representation of the frequency in which a color is used, so I wrote my own. The difference with other gamut visualizers is that the colors that are less used will be more transparent than the ones that are more frequently used. This allows you to have more information about color usage and helps you determine which zones of the color wheel have been used more in the image.

Making it has provided me a chance to learn a little bit of the Paper.js framework. I could have probably made it with just JavaScript and a canvas element but Paper.js made the process pretty easy. One of the features of Paper.js is that it provides you with PaperScript, an extension to JavaScript that makes working with Paper.js even easier.

On the html side of things I've adapted the code found on to implement drag and drop from the filesystem, but I had a little bit of trouble connecting the JavaScript on the html page with my PaperScript. I wanted to access a function from the PaperScript from the html page and to also set a variable, however, I couldn't find how to do that in the Paper.js documentation.

After some searching I found the solution in the Paper.js Google Group, so I'm passing it along hoping to increase its visibility. The trick consists of creating a global object from PaperScript that will hold all the functions and variables that you want to pass along without polluting too much the global scope, only with this object holding all the rest under it.

In my case, I've created an object called 'paperscript' and added to it a function and a couple of variables with default values that I wanted to be accessible from JavaScript:

// Inject a global object to be able to call clear() and to set some variables from JavaScript.
window.paperscript = {};

paperscript.clear = function () {

// Change these from JavaScript if needed:
paperscript.backgroundColor = "white";
paperscript.radius = 150;

I've created a repository on GitHub for the gamut visualizer in case you want to take a look at its code or do something with it.



Roger Tallada's blog.

A former developer who changed career to illustration, now going back to development.