Drawing Stars
Finally, Star's draw() method actually draws the star to the canvas. Once again, we're using fill() and ellipse(), although this time we're calling fill() with a grayscale value and an alpha value for transparency. To give the stars a twinkle, the alpha value is determined using p5's noise() function.
This returns the Perlin noise value for the specified coordinates, meaning you get a smooth, fluid sequence of random numbers. For the third parameter, we're passing a time-based value rather than a spatial value, so that the noise will animate over time.
Star.prototype.draw = function() {
var alpha = noise(
this.target.x,
this.target.y,
millis()/1000.0
);
fill(255, alpha * 255);
ellipse(
this.position.x, this.position.y,
this.diameter, this.diameter
);
};
That's it for our first sketch! Click and drag to see new stars appear and conform to the hint image.
What's next?
From here, you might add some HTML elements to control variables using the p5.dom add-on or even add sound to the visuals using p5.sound.
We've only scratched the surface of what's possible with p5.js, and with new features and an official editor on the way, there's even more to look forward to. Have fun!
Words: Scott Garner
Scott Garner is an expert in creative technology and interactive design. Follow him on Twitter at @scottgarner. This article first appeared in net magazine issue 261.
Like this? Read this!
- Free Photoshop brushes every creative must have
- Free Photoshop actions to create stunning effects
- The best Photoshop plugins