Paper.js Interoperability

2020-02-07 01:47发布

I would like to call paper.js functions from HTML buttons in my page but I believe the paper.js functions exist in their own scope. The paper.js docs mention interoperability which sounds like the right direct by then take me to a page that says "coming soon":

http://paperjs.org/tutorials/getting-started/paperscript-interoperability/

Does anyone know how I can call a function created within a paper.js script from my HTML page?

2条回答
放荡不羁爱自由
2楼-- · 2020-02-07 02:08

Apologies for that missing tutorial. I shall really invest some time into writing it finally.

I've answered this question on the mailing list last year: https://groups.google.com/d/msg/paperjs/C6F0XFlplqM/_67AMqCR_nAJ

Scoped PaperScript run inside the global scope, and have access to all elements of the global scope. The normal JavaScripts running in the global scope (= window) will not see these PaperScopes, and won't have access to their variables.

There is a simple solution to exchange information between the two: Simply declare a global structure that you use to exchange tings back and forth, e.g.

window.globals = {
    someValue: 10,
    someFunction: function() { alert(globals.someValue); }
};

In your PaperScript, you can then access this simply through 'globals', since it's in the window scope:

globals.someValue = 20;
globals.someFunction();

And in the same way, you can use this structure from normal JavaScript.

查看更多
贼婆χ
3楼-- · 2020-02-07 02:18

I just wanted to add some clarification for anyone who runs into this.

For PaperScript-to-JavaScript interoperability, do the following...

In HTML file:

<button type="button" id="btn">Click Me!</button>

In JavaScript file:

$(document).ready(init);

function init(jQuery) {
  $("#btn").click(window.globals.paperClicked);
}

// PaperScript Interop
window.globals = {
  paperClicked: function() {}
}

In PaperScript file:

// JavaScript Interop
globals.paperClicked = internalClicked;

function internalClicked() {
  alert('clicked!');
}
查看更多
登录 后发表回答