Drawing A Mouse Trace

Example of Storing Mouse Data in an Array

(from the blue Processing Book, page 308)

int num = 50;
int[] x = new int[num];
int[] y = new int[num];
int indexPosition = 0;
void setup() {
  size (100, 100);
  fill(255, 102);
void draw() {
  // Store the mouse data at the indexPosition in the array
  x[indexPosition] = mouseX;
  y[indexPosition] = mouseY;
  // Wrap the indexPosition back to the start of the array when it reaches the end
  indexPosition = (indexPosition + 1) % num;
  // Cycle between 0 and the number of elements
  for (int i = 0; i < num; i++) {
    // Set the array position to read
    int pos = (indexPosition + i) % num;
    float radius = (num-i) / 2.0;
    ellipse(x[pos], y[pos], radius, radius);

In this improved example we avoid copying all the stored mouse data every frame. This makes the example much more efficient for big sets of data (long arrays), because having to copy all that data each frame could easily slow down your program.
Instead we keep a position counter indexPosition with which we remember where in the array the last stored mouse data is.
We use the % operator (Modulo, see Processing reference for modulo or page 45 from the book), to wrap the indexPosition back to the beginning when it reaches the end of the array.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License