How can I move those 6 rectangles. I think i have to change the X and the Y for the loop, but I don't know how. I would love some help.
This is the code: https://editor.p5js.org/AlexArek/sketches/r1eVquBkV
let cols = 3;
let rows = 3;
function setup() {
createCanvas(600, 600);
}
function draw() {
background(90, 140, 210);
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
let x = i * 110;
let y = j * 110;
noFill()
rect(x, y, 100, 100)
}
}
//How can I move this whole thing in the middle of the screen?
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/p5.js"></script>
First you have to calculate the box (width and height) of your object:
let obj_w = 110 * (cols-1) + 100;
let obj_h = 110 * (rows-1) + 100;
Then you have to move the the center of the object to the center of the canvas by translate()
.
The built in variables width
and height
contain the size of the canvas.
If you would move by the half of the canvas size, then the upper left corner of the object would be in the center of the canvas:
translate(width/2, height/2);
If you move in the opposite direct by the half size of the object, then the center of the object is in the center of the canvas:
translate(-obj_w/2, -obj_h/2);
let cols = 3;
let rows = 3;
function setup() {
createCanvas(600, 600);
}
function draw() {
background(90, 140, 210);
let obj_w = 110 * (cols-1) + 100;
let obj_h = 110 * (rows-1) + 100;
translate(width/2, height/2);
translate(-obj_w/2, -obj_h/2);
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
let x = i * 110;
let y = j * 110;
noFill()
rect(x, y, 100, 100)
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/p5.js"></script>