-1

Below are codes through which I was trying to achieve the hue property on a grid of circles.

var circles = [];

for(var i=20 ; i<=1500 ; i+=100){
  for(var j=40 ; j<=600 ; j+=110){
    var newCircle = new Path.Circle(new Point(i, j), 20);
    newCircle.fillColor = 'red';
    circles.push(newCircle);
  }
}

function onFrame(event){
  for(var i=0 ; i<circles.length ; i++ ){
    circles[i].fillColor.hue += 1;
  }
}

This is the code. Now I am trying to give different colors to each circle using the random color func I created in a seperate JS file but the variables like "num" aren't accessible in that js file.I am not able to link them.

This is the link to codepen : https://codepen.io/akashyap/pen/qMgpGQ

I am not able to figure out the " Using paperscript directly with javascript" section of :

http://paperjs.org/tutorials/getting-started/using-javascript-directly/

  • 1
    Can you edit the question and add your random color function, how you're loading it, and how you're trying to call it? – Jacob Sep 19 '18 at 21:56
  • Hello Jacob ! Thank you for replying. I have attached a link to codepen , please check it out. – Akash Singh Sep 20 '18 at 14:33
  • Thanks for providing the code, but please edit the question and add the code there as well. You are also able to do runnable code snippets in Stack Overflow. – Jacob Sep 20 '18 at 15:41
  • I actually figured it out :p .. But can you please explain how to use paper js directly in Javascript file ? – Akash Singh Sep 20 '18 at 16:59

1 Answers1

0

You're running across a timing issue. When your plain JS runs, circles is not yet defined. That's because your paper script is inside of a <script type="text/paperscript"> element. This is not natively supported by the browser so it won't be run right away. Rather, some time after you load paper.js, it eventually reads your script element and interprets it.

You need to make sure you don't try to access circles before it's defined. If it is unpredictable when your paperscript will be ready, you can use a callback to notify external JS when the paperscript has run. For example, if you add this to your paperscript:

if (window.onCirclesReady)
  window.onCirclesReady(circles);

...you can wrap your JS in this:

window.onCirclesReady = circles => {
  // Code here
};

This solves two problems. Firstly, you know your JS code won't run until the paperscript has run. Secondly, you are passing the circles array so you don't have to use a global variable to make that accessible. You can extend the callback to pass additional data as needed.

The updates to your CodePen are here

Jacob
  • 77,566
  • 24
  • 149
  • 228