Skip to content
Advertisement

Cursor trail algorithm for p5.js

I found this little coding exercise on Processing’s website (https://processing.org/examples/storinginput.html) and decided to make a p5.js version of it.

The part that I do not understand about this algorithm is how the ellipses drawn (in the trail) shrinks when variable i, which is used as the scale of the ellipse, is increasing. I suspect that it has something to do with the value of variable index but I am unable piece it together.

Does anyone know how this algorithm works? Any help would be appreciated.

Here is the Javascript version of code:

var num = 60;
var mx = []; 
var my = []; 

function setup() {

  createCanvas(windowHeight, windowHeight);
  noStroke();
  fill('rgba(0,0,0, 0.5)');
  noCursor();

}

function draw() {

  background(255);

  var array_pos = (frameCount) % num; 
  mx[array_pos] = mouseX; 
  my[array_pos] = mouseY; 


  for (var i = 0; i < num; i++) {
    var index = (array_pos + 1 + i) % num; 
    ellipse(mx[index], my[index], i, i); 
  }

}

Advertisement

Answer

The current mouse position is stored in an array in every frame. When the array is full, it will be filled again from the beginning. This is achieved using the modulo (%) operator (% computes the remainder of a division).

var array_pos = frameCount % num; 
mx[array_pos] = mouseX; 
my[array_pos] = mouseY; 

The diameter of the circle depends on the control variable of the loop (i). The smallest circle is the circle with index array_pos + 1. Therefore with i == 0 the circle with the index array_pos + 1 is drawn. The following circles become larger as i increases. Again, the modulo operator (%) is used to prevent the array from being accessed out of bounds.

var index = (array_pos + 1 + i) % num; 

var num = 60;
var mx = []; 
var my = []; 

function setup() {
    createCanvas(windowWidth, windowHeight);
    noCursor();
}

function draw() {
    var array_pos = frameCount % num; 
    mx[array_pos] = mouseX; 
    my[array_pos] = mouseY; 

    background(255);
    noStroke();
    fill(255, 0, 0, 127);
    for (var i = 0; i < num; i++) {
        var index = (array_pos + 1 + i) % num; 
        ellipse(mx[index], my[index], i, i); 
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.min.js"></script>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement