Search code examples
paperjs

Call a function inside paperscript from outside


I have 3 JS file.

  1. main.js
  2. map.js
  3. legend.js

map.js and legend.js are paperscripts for 2 different canvases. They are called from HTML like this.

<script type="text/javascript" src="main.js"></script>
<script type="text/paperscript" src="map.js" canvas="mapCanvas"></script>
<script type="text/paperscript" src="legend.js" canvas="legendCanvas"></script>

in map.js, we have a function named drawMap()

in legend.js, we have a function named drawLegend()

obviously they manipulate their own canvases.

Requirement: I want to call those functions from main.js.

I have seen this post Paperscope and paperjs

and followed these instructions https://groups.google.com/forum/#!msg/paperjs/C6F0XFlplqM/_67AMqCR_nAJ

But I'm not sure how and where to build and call PaparScope objects.

Still not working.

This is close: Paper.js Interoperability

But what I need is the other way around.


Solution

  • You need to export the functions that you want to call from the outside, e.g.:

    window.drawMap = drawMap;
    window.drawLegend = drawLegend;
    

    Then they become globals and you can call them from outside.

    A more elegant way may be to define a container in the global scope, e.g. (in a normal JavaScript script tag that is executed before the PaperScript code, e.g. in your main.js):

    var globals = {};
    

    And then access and fill this container from the PaperScript in the same way:

    globals.drawMap = drawMap;
    globals.drawLegend = drawLegend;
    

    After that, you can use them from any JavaScript or PaperScript:

    globals.drawMap();
    globals.drawLegend();
    

    Update:

    Since you work with more than one PaperScope (as created by the PaperScript code bound to separate canvases), you need to activate the right scope before calling the function that deals with the given canvas. It's best to do that in your drawMap() and drawLegend() functions directly, so you don't have to worry when calling from outside.

    Inside the PaperScript, this points to the scope, so you could do something like this, outside the function:

    var scope = this;
    

    and then inside the function:

    scope.activate();