Ask coding questions

← Back to all posts
random color in fill and background (p5js)
upsideumop (6)

I need help putting a random color in fill and background. my code is below:
function setup() {
createCanvas(windowWidth, windowHeight);
const colors = ["red","blue","green"];
const random = Math.floor(Math.random() * colors.length);
var d = createButton('Save')
d.mousePressed(savecanvas);
d.size(windowWidth, 30)
}
function savecanvas() {
saveCanvas('doodle', 'png')
}

function draw() {
background(${random});
if (mouseIsPressed) {
fill(${random})
}
ellipse(mouseX, mouseY, 5, 5);
}

Answered by Coder100 (16983) [earned 5 cycles]
View Answer
Comments
hotnewtop
Coder100 (16983)

you can use the random function instead:

  const colors = ["red","blue","green"];
  let color;

function setup() {
  createCanvas(windowWidth, windowHeight);
color = random(colors);
  var d = createButton('Save')
  d.mousePressed(savecanvas);
  d.size(windowWidth, 30)
    }
    function savecanvas() {
      saveCanvas('doodle', 'png')
}

function draw() {
  background(`${color}`);
  if (mouseIsPressed) {
  fill(`${color}`);
}
  ellipse(mouseX, mouseY, 5, 5);
}

also your variables need to be outside of the function too

tussiez (1510)

Truly random:

const makeColor = () => {
return `rgb(${Math.random()*255},${Math.random()*255},${Math.random()*255})`
}
xxpertHacker (855)

@tussiez Legit wrote a program to demonstrate memory reinterpretation, using colors and HTML canvases: https://replit.com/@xxpertHacker/canvas-color, similar idea for the ransoms though.