我正在p5.js中绘制一些旋转的矩形,并且一切正常。然后,我需要在矩形顶部显示一些文本,并且希望它保持不动。但是,文本也在旋转。我已经尝试了一些解决方案,例如将rotate(0)设置为值或对最后绘制的矩形的旋转值设置负值,但没有任何效果。
class Rectangle {
constructor(size, colorR, colorG, colorB, angle) {
this.size = size;
this.colorR = colorR;
this.colorG = colorG;
this.colorB = colorB;
this.angle = angle;
this.actualAngle = this.angle;
}
draw() {
stroke(0);
strokeWeight(2);
fill(this.colorR, this.colorG, this.colorB);
rotate(this.actualAngle);
rect(0, 0, this.size, this.size);
}
increaseAngle() {
this.actualAngle += this.angle;
}
getActualAngle(){
return this.actualAngle;
}
}
var rectangles = [];
function setup() {
var canvas1 = createCanvas(800, 700);
canvas1.parent("regLog");
var size = 12;
for (var i = 0; i < 10; i++) {
let ranR = random(150);
let ranG = random(150);
let ranB = random(150);
let angle = random(-0.005, 0.005);
rectangles.push(new Rectangle(size, ranR, ranG, ranB, angle));
size += 50;
}
}
function draw() {
background(255);
rectMode(CENTER);
translate(width / 2, height / 2);
for (var i = rectangles.length - 1; i > 0; i--) {
rectangles[i].draw();
}
if (second() % 1 == 0) {
for (let i = 0; i < rectangles.length; i++) {
rectangles[i].increaseAngle();
}
}
rotate(0);
noStroke();
fill(255, 255, 255, 0);
rect(0, 0, 50, 50);
textAlign(CENTER);
fill(255);
textSize(60);
text("Coming soon!", 0, 0);
}
答案 0 :(得分:1)
我使用push()“保存”当前旋转设置,然后在每次绘制矩形后使用pop()恢复它们。当您使用rotate()时,它将旋转您绘制的所有将来的形状,因此除非您非常小心地进行重置,否则更改是“永久的”。
您可以在jsfiddle中看到它的工作原理-> https://jsfiddle.net/ozsLtxhb/237/
我注释掉了您为jsfiddle分配一个父级的部分,因此在将其复制粘贴到任何内容之前,请先取消注释
class Rectangle {
constructor(size, colorR, colorG, colorB, angle) {
this.size = size;
this.colorR = colorR;
this.colorG = colorG;
this.colorB = colorB;
this.angle = angle;
this.actualAngle = this.angle;
}
draw() {
/*push here*/
push();
stroke(0);
strokeWeight(2);
fill(this.colorR, this.colorG, this.colorB);
rotate(this.actualAngle);
rect(0, 0, this.size, this.size);
/*pop here*/
pop();
}
increaseAngle() {
this.actualAngle += this.angle;
}
getActualAngle(){
return this.actualAngle;
}
}
var rectangles = [];
function setup() {
var canvas1 = createCanvas(800, 700);
/* canvas1.parent("regLog"); */
var size = 12;
for (var i = 0; i < 10; i++) {
let ranR = random(150);
let ranG = random(150);
let ranB = random(150);
let angle = random(-0.005, 0.005);
rectangles.push(new Rectangle(size, ranR, ranG, ranB, angle));
size += 50;
}
}
function draw() {
background(255);
rectMode(CENTER);
translate(width / 2, height / 2);
for (var i = rectangles.length - 1; i > 0; i--) {
rectangles[i].draw();
}
if (second() % 1 == 0) {
for (let i = 0; i < rectangles.length; i++) {
rectangles[i].increaseAngle();
}
}
rotate(0);
noStroke();
fill(255, 255, 255, 0);
rect(0, 0, 50, 50);
textAlign(CENTER);
fill(255);
textSize(60);
text("Coming soon!", 0, 0);
}