【问题标题】:How to move some rectangles made with the Loop function如何移动使用循环功能制作的一些矩形
【发布时间】:2018-12-05 16:20:59
【问题描述】:
如何移动这 6 个矩形。
我想我必须更改循环的 X 和 Y,但我不知道如何。我很想得到一些帮助。
这是代码: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>
【问题讨论】:
标签:
for-loop
processing
rectangles
p5.js
【解决方案1】:
首先您必须计算对象的框(宽度和高度):
let obj_w = 110 * (cols-1) + 100;
let obj_h = 110 * (rows-1) + 100;
然后你必须将对象的中心移动到画布的中心translate()。
内置变量width 和height 包含画布的大小。
如果您移动画布大小的一半,那么对象的左上角将位于画布的中心:
translate(width/2, height/2);
如果你向相反方向直接移动对象的一半大小,那么对象的中心就在画布的中心:
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>