2

I want to load predefined colors into my p5js file.

I tried the following:

let module = require('./colors.js');

// noprotect
function setup() {
  createCanvas(windowWidth, windowHeight);

  // generate background
  colorMode(HSB);
  background(5, 10, 100);

  colorization(module.colors);

}

function colorization() {

  // 2. colors from file
  let colorArr = module.colors;
  console.log(colorArr[1])

  const randomElement = colorArr[Math.floor(Math.random() * colorArr.length)];
  console.log(colorArr[randomElement])

}
<!DOCTYPE html>
<html>

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/p5.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/addons/p5.dom.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/addons/p5.sound.min.js"></script>
  <script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/simple-statistics/7.8.0/simple-statistics.min.js" integrity="sha512-xDFZFTH4OUC3OXrn92+YDyIq7VOQDTSAfcAy2kc9h9Wp/BiGwGVPDCDT2CXy6Aml2j+8AMX98jgdk5gZPcsfbw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

  <link rel="stylesheet" type="text/css" href="style.css">
  <meta charset="utf-8" />

</head>

<body>
  <div id="palette"></div>
  <script src="sketch.js"></script>
</body>

</html>

The colors I want to load are in my colors.js file:

exports.colors = [
  "#c0a8a8",
  "#a8a890",
  "#90a8c0",
  "#d8d8d8",
  "#90c0d8",
  "#f0f0f0",
  "#a8c0c0",
  "#30a8c0",
  "#d89078",
  "#f09000",
  "#009090",
  "#fffff0",
  "#a8d8d8",
];

I get the error ReferenceError: require is not defined.

Any suggestions how to load the array of colors into my code?

I appreciate your replies!

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
Carol.Kar
  • 4,581
  • 36
  • 131
  • 264
  • 1
    `require()` is specific to node.js, which I assume you're not using. Instead of that, use a plain JS `import`: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import – Gerardo Furtado Dec 31 '22 at 10:36

0 Answers0