如何解决数组返回不一致p5js
在绘图程序中,线坐标存储在数组中,以便可以重绘绘图。有时,返回的图像并不完全完整,并且在按下鼠标之前这几行都丢失了(在p5js中)。我不确定如何解决此问题(对不起,我对此很陌生)。
let lineCor = [];
let state = "help";
let r,g,b;
let symmetry = 8;
let angle = 360 / symmetry;
function setup() {
createCanvas(windowWidth,windowHeight);
background(220);
r = 50;
g = 0;
b = 0;
}
function draw() {
helpScreen();
copyDrawing();
}
function copyDrawing() {
if (state === "draw") {
push();
angleMode(DEGREES);
translate(windowWidth / 2,windowHeight / 2);
displayImg();
pop();
if (mouseIsPressed) {
let linePos = {
x: mouseX - windowWidth / 2,y: mouseY - windowHeight / 2,px: pmouseX - windowWidth / 2,py: pmouseY - windowHeight / 2,};
lineCor.push(linePos);
}
}
}
function displayImg() {
stroke(r,b);
for (let i = 0; i < symmetry; i++) {
for (let n = 0; n < lineCor.length; n++) {
rotate(angle);
line(lineCor[n].x,lineCor[n].y,lineCor[n].px,lineCor[n].py);
push();
scale(1,-1);
line(lineCor[n].x,lineCor[n].py);
pop();
}
}
}
function mouseWheel() {
if (event.deltaY > 0) {
if (r < 255) {
r += 10;
}
else if (g < 255) {
g += 10;
}
else if (b < 255) {
b += 10;
}
} else {
if (r > 0) {
r -= 10;
}
else if (g > 0) {
g -= 10;
}
else if (b > 0) {
b -= 10;
}
}
}
function helpScreen() {
if (state === "help") {
background(160);
textAlign(CENTER,CENTER);
textSize(windowWidth * 0.04);
text("Welcome to this kaleidiscope drawing program",windowWidth / 2,windowHeight / 3);
textSize(windowWidth * 0.015);
text("To change color,scroll the mousewheel. Press 's' to start drawing. Press 'c' to clear the screen. Press 'h' to return to return to this help screen.",1.5 * windowHeight / 3);
}
}
//commands for the keybinds
function keyTyped() {
if (key === "c") {
setup();
lineCor = [];
}
if (key === "h") {
setup();
state = "help";
}
if (key === "s") {
setup();
state = "draw";
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.1.9/p5.min.js"></script>
解决方法
问题在这里:
for (let i = 0; i < symmetry; i++) {
for (let n = 0; n < lineCor.length; n++) {
rotate(angle);
line(lineCor[n].x,lineCor[n].y,lineCor[n].px,lineCor[n].py);
push();
scale(1,-1);
line(lineCor[n].x,lineCor[n].py);
pop();
}
}
在调试时,我发现问题是由于background()
而产生的,这必须表示未绘制所有线条。经过进一步的实验,我发现它仅在lineCor具有偶数个元素时发生。为什么会这样?
由于rotate()
。您会看到,旋转应该只发生8次(let symmetry = 8
),但是在您的代码中,旋转发生在每一行。
当lineCor.length
为偶数时,这会导致它多次在同一位置绘制线条(看起来好像根本没有绘制任何线条)。
可以通过将rotate()
移动到外部for循环来轻松解决此问题。
for (let i = 0; i < symmetry; i++) {
rotate(angle);
for (let n = 0; n < lineCor.length; n++) {
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。