Use GreenSock in P5.js editor

โ€ข 5 min read

P5.js is a great library to create dynamic and interactive sketches.

Itโ€™s often used by creative people who knows how to code (creative coders) and by a lot of creatives in general that want to approach coding matter.

Indeed, P5.js (and Processing) has been always the perfect tool to start learning coding.

What is a little bit more challenging in p5.js is making animations, if compared with what some popular javascript libraries can do with very few lines of codes, such as GreenSock (also known as GSAP).

I wanted to investigate on possible outcomes by integrating P5.js with GSAP and keeping the barrier the lowest as possible for newbies and primers.

The setup #

Iโ€™m using the P5.js online editor because itโ€™s the fastest setup we can imagine, just head to its URL, create and account, and youโ€™re ready to code.

The only extra step we need to do is to include the GSAP library within the scketch.

Add the following code within the head in the index.html file:

<script src="https://unpkg.com/gsap"></script>

P5 context #

P5.js draws shapes and elements on a canvas by means of sequential drawing calls. This means that all the shapes, elements and their properties, once drawn, are not available anymore and a new frame needs to be re-drawn from scratch.

GSAP (and other similar libraries), instead, animates existing properties over time, meaning that those properties need to be available across several frames.

Proxy variables #

In order to make GSAP useful in P5.js context, we need some properties that act as proxy:

var x = 0
var y = 0

function draw(){
  circle(x, y, 50)
}

function mouseClicked(){
  gsap.to(this, {x:100, y:100})
}

In this case we pass this to GSAP because x and y are public property of the P5 context.

Click to interact ๐Ÿ‘‡ (source):

This works fine but for each element we want to animate, we need, at least, a pair of variables. This is not going to scale.

Letโ€™s try to abstract the elements we want to animate with GSAP:

var elements = []

function setup() {
  createCanvas(400, 400);
  for(var i=0; i<50; i++){
    elements.push({
      x: width/2,
      y: height/2,
      r: 2
    })
  }
}

and in the draw function we can put simply this:

function draw(){
  background(255)
  elements.forEach(el => {
    circle(el.x, el.y, el.r)
  })
}

Now we need the trigger to start the GSAP animations:

function mouseClicked(){
  gsap.to(elements, {
    x:() => random(width), 
    y:() => random(height), 
    r:() => random(40), 
    stagger:0.1})
}

Click to interact ๐Ÿ‘‡ (source):

Of course, everything that is a number can be animated with GSAP:

Click to interact ๐Ÿ‘‡ (source):

And by extension, here the same above example with the abstraction technique in order to draw many boxes, click to interact ๐Ÿ‘‡, then press 1 (source)

So far, so good. Happy exploration!