Skip to content
Advertisement

Randomize assigned colors in an array in p5.js

I have been trying to recreate one of Vera Molnar’s paintings, and to add a twist, I wanted to randomize the colors in the array as I drag my mouse over the canvas. However, I cannot for the life of me figure out how to do this. Below is one of many attempts at this. What could I be doing wrong?

As for the colors, the intial order of the colors is something I would like to keep, as it is directly mimicking the original painting, but as the mouse is moved into the canvas/frame, i want to trigger the random colors.

Thank you for your help!

const width = 700;
const height = 700;

let radius = 58;
let len = 8;
let color;
let colors;

function setup() {
  createCanvas(width, height);

  colors = [
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#d31a22",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#e2592f",
    "#d31a22",
    "#9bd6ff",
    "#9bd6ff",
    "#e2592f",
    "#9bd6ff",
    "#9bd6ff",
    "#000000",
    "#000000",
    "#9bd6ff",
    "#9bd6ff",
    "#000000",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#000000",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#d31a22",
    "#e2592f",
    "#000000",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#000000",
    "#9bd6ff",
    "#e2592f",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#d31a22",
    "#000000",
    "#000000",
    "#9bd6ff",
  ];
}

function draw() {
  background(255);

  for (let i = 0; i < len; i++) {
    for (let j = 0; j < len; j++) {
      let x = i * 80;
      let y = j * 80;
      color = colors.shift();
      if (color === undefined) {
        color = "white";
      }
      fill(color);
      noStroke();
      ellipse(y + 65, x + 65, radius);
    }
  }

  noLoop();
}

function mouseDragged() {
  color = random(colors);
}

Advertisement

Answer

If you want to change color for a specific ellipse, you might need to calculate the position based on mouseX and mouseY coordinates.

In this sketch – https://editor.p5js.org/yeren/sketches/7SCNsEMo_, I’m simply shuffling the color array when the mouse is moved over the canvas.

Also, if possible avoid mutating the array.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement