We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi,
I am trying to create a class of circles in p5.js and draw them. It is fairly simple. I am trying to adapt a piece of code from processing to p5.js and my 'for in' statement does not work and I get an error ' Uncaught SyntaxError: Unexpected identifier '
I don't understand completely why this is not working and what I should change in this code.
Any help regarding creating a class in p5.js would be much appreciated.
Thanks,
Omer
var canvasOfset = 10;
var circles;
function setup() {
circles = new Array();
createCircles();
createCanvas(windowWidth - canvasOfset, windowHeight - canvasOfset);
frameRate(30);
background(0);
}
function createCircles() {
for (var i = 0; i < windowWidth; i++) {
if (i % 100 == 0) {
circles.push(new Circle(i, i, 100))
}
}
}
function draw() {
background(0, 5);
for (Circle c in circles) {
ellipse(c.x, c.y, c.scale);
fill(255, 0, 0);
noStroke();
}
}
class Circle {
constructor(x, y, scale) {
this.x = x;
this.y = y;
this.scale = scale;
}
}
function windowResized() {
resizeCanvas(windowWidth - canvasOfset, windowHeight - canvasOfset);
}
Answers
Sorry, I believe it should be
for (Circle c : circles) {
not
https://Developer.Mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of
@omerpekin - p5js is JavaScript; so isn't a typed language... So you don't define the
c
variable in your loop as aCircle
; but just use a general variable declaration likevar
; or these daysconst
orlet
:BUT -
for...in
is NOT a good choice of loop to use on Objects in JS (see this); which leads to @GoToLoop's suggestion: for...of is the safer option to iterate over Objects ;)Hi,
Thank you very much for your answers. Finally, I managed it the simpler way ( I guess) or at least the way I understand. This is how my code looks like:
for (var i = 0; i < circles.length; i++) {}