我正在尝试从我创建的一系列书籍中创建一个书架,并且如果"推荐"则通过对角线书写一本书。该书的财产是" false"。您可以在我的for
循环中看到我尝试使用以下if语句执行此操作:
if(books[i].recommended === false)
{
fill(0, 0, 0);
line(bookX,bookY,bookX+90,bookY+100);
}
但是我的问题是我在for
循环中创建的行在后面,在我的书后面,因此是不可见的。我怎样才能让它走到前台呢?
以下完整代码:
//I create my array with my books
var books = [];
for(var y = 1;y<=20;y++)
{
books.push(
{
title: "Book "+y,
stars: random(4),
author: "Author "+y,
color: color(random(255), random(255), random(255)),
recommended: !!Math.floor(Math.random() * 2)
}
);
}
// Loop to draw 3 shelves
var shelfY = 105;
while (shelfY<=360)
{
fill(173, 117, 33);
rect(0, shelfY, width, 10);
shelfY +=120;
}
// Loop to draw all my books
var bookX = 5;
var bookY = 5;
for (var i = 0; i<books.length; i++)
{
fill(books[i].color);
rect(bookX, bookY, 90, 100);
fill(0, 0, 0);
text(books[i].title, bookX+5, bookY+9, 70, 100);
text(books[i].author, bookX+5, bookY+24, 70, 100);
for (var j = 0; j < books[i].stars; j++)
{
image(getImage("cute/Star"), bookX+3 + j * 20, bookY+70,20, 30);
}
bookX += 100;
if(bookX>400)
{
bookX = 5;
bookY += 120;
}
if(books[i].recommended === false)
{
fill(0, 0, 0);
line(bookX,bookY,bookX+90,bookY+100);
}
}
答案 0 :(得分:1)
你在增加bookX和bookY后画线,所以它不会在正确的地方画出。
尝试将你的if(books [i] .recommended等...放在bookX + = 100之前;它会起作用。
这是最终的代码:
//I create my array with my books
var books = [];
for(var y = 1;y<=20;y++)
{
books.push(
{
title: "Book "+y,
stars: random(4),
author: "Author "+y,
color: color(random(255), random(255), random(255)),
recommended: !!Math.floor(Math.random() * 2)
}
);
}
// Loop to draw 3 shelves
var shelfY = 105;
while (shelfY<=360)
{
fill(173, 117, 33);
rect(0, shelfY, width, 10);
shelfY +=120;
}
// Loop to draw all my books
var bookX = 5;
var bookY = 5;
for (var i = 0; i<books.length; i++)
{
fill(books[i].color);
rect(bookX, bookY, 90, 100);
fill(0, 0, 0);
text(books[i].title, bookX+5, bookY+9, 70, 100);
text(books[i].author, bookX+5, bookY+24, 70, 100);
for (var j = 0; j < books[i].stars; j++)
{
image(getImage("cute/Star"), bookX+3 + j * 20, bookY+70,20, 30);
}
if(books[i].recommended === false)
{
fill(0, 0, 0);
line(bookX,bookY,bookX+90,bookY+100);
}
bookX += 100;
if(bookX>400)
{
bookX = 5;
bookY += 120;
}
}