简体   繁体   English

在 p5.js 的数组中随机分配 colors

[英]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.我一直在尝试重现 Vera Molnar 的一幅画作,并添加了一个转折点,我想在将鼠标拖到 canvas 上时随机化数组中的 colors。但是,我这辈子都不知道该怎么做这个。 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.至于colors,我想保留colors的初始顺序,因为它直接模仿原画,但是当鼠标移入画布/框架时,我想触发随机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);
}

If you want to change color for a specific ellipse, you might need to calculate the position based on mouseX and mouseY coordinates.如果要更改特定椭圆的颜色,您可能需要根据 mouseX 和 mouseY 坐标计算 position。

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.在此草图 - https://editor.p5js.org/yeren/sketches/7SCNsEMo_中,当鼠标移到 canvas 上时,我只是简单地洗牌颜色数组。

Also, if possible avoid mutating the array.另外,如果可能的话,避免改变数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM