Reputation: 11
I am trying to push colors into an array in p5.js except it won't let me, here is my code, could someone please tell me why?
var colors = [];
colors.push( color(255, 0, 0, 0) );
colors.push( color(255,127, 0,255) );
colors.push( color(255,255 ,0,255) );
colors.push( color( 0,255, 0,255) );
colors.push( color( 0, 0,255,255) );
colors.push( color( 75, 0,130,255) );
colors.push( color(148, 0,211,255) );
It reports this error:
brick.js:2 Uncaught ReferenceError: color is not defined
at brick.js:2
Upvotes: 0
Views: 996
Reputation: 462
The problem is that you are calling the p5 function color
before setup()
is called. Why this happens is explained in detail here.
I have made a working example of how you might do it below.
let colors;
function setup() {
createCanvas(150, 150);
background(238);
colors = [];
colors.push( color(255, 0, 0, 0) );
colors.push( color(255,127, 0,255) );
colors.push( color(255,255 ,0,255) );
colors.push( color( 0,255, 0,255) );
colors.push( color( 0, 0,255,255) );
colors.push( color( 75, 0,130,255) );
colors.push( color(148, 0,211,255) );
}
function changeColor() {
background(random(colors));
}
button {
display: block;
margin: 10px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.1/p5.min.js"></script>
<button onclick='changeColor()'>Choose color from array</button>
Upvotes: 1