2014-01-22 4 views
0

Я сделал несколько прямоугольников, используя цикл. Цвет прямоугольников предоставляется из массива.Заполнить фон цветом из массива при нажатии на прямоугольник

Я хочу, чтобы щелкнуть по одному из прямоугольников, этот фон заполняется цветом, который я выбрал.

Я новичок в обработке, поэтому я немного смущен о том, как это сделать.

color[] backgrounds = {#e8be55, #ff8827, #eb5051, #00b4cc, #005f6b, #7c6753, #edeaee}; 
int bgLength = backgrounds.length; 

int xPos; 
int yPos; 
int size; 

void setup(){ 
background(255); 
size(1024, 768); 
} 

void draw(){ 
size = 40; 
    xPos = guide + 10; 
    yPos = 167; 

    for(int i = 0; i < bgLength; i++) { 
    noStroke(); 
    fill(backgrounds[i]); 
    rect(xPos, yPos, size, size); 
    xPos = xPos + size + 4; 

     if(xPos>180){ 
       xPos = guide + 10; 
       yPos += size + 4; 

     } 
    } 
} 

Спасибо.

ответ

0

Вы должны проверить границы. Сначала я предлагаю вам немного упорядочить переменные. Например, некоторые переменные никогда не меняются (поэтому нет причин назначать их в draw()). Это должно облегчить просмотр координат.

Я предлагаю это:

color[] backgrounds = {#e8be55, #ff8827, #eb5051, #00b4cc, #005f6b, #7c6753, #edeaee}; 
int bgLength = backgrounds.length; 

int xOffset = 10; 
int yOffset = 167; 
int xPos; 
int yPos; 
int size = 40; 
int guide = 10; 
int cols = 4;//4 columns 

color selectedBackground = backgrounds[backgrounds.length-1];//default to last element in the list/array 

void setup(){ 
    background(255); 
    size(1024, 768); 
    noStroke(); 
} 

void draw(){ 
    background(selectedBackground); 

    for(int i = 0; i < bgLength; i++) { 
    xPos = xOffset + ((i % cols) * (size+guide));//since % is returns the remainder of division, we use it to compute x position in the grid 
    yPos = yOffset + ((i/cols) * (size+guide));//and we divide by the number of columns to compute the y position in the grid 

    fill(backgrounds[i]); 
    //check if a box is clicked 
    if((mouseX >= xPos && mouseX <= xPos+size) && //check horizontal bounds(left/right) 
     (mouseY >= yPos && mouseY <= yPos+size)){ //check vertical bounds(top/bottom) 
     if(mousePressed){//if mouse is over/within a boxes bounds and clicked 
      selectedBackground = backgrounds[i];//set the colour based on id 
     }else{//just hovering 
      fill(backgrounds[i],127);//draw transparent colour, just to high light selection, not actually needed, but now an easy option 
     } 
    } 
    rect(xPos, yPos, size, size);//we draw at the end because the fill colour might have changed if a box was hovered 
    } 
} 

Вы можете запустить яваскрипт демонстрационные ниже. (Хотя есть небольшие различия в синтаксисе, понятие ядра того же):

var backgrounds;// = [color('#e8be55'), color('#ff8827'), color('#eb5051'), color('#00b4cc'), color('#005f6b'), color('#7c6753'), color('#edeaee')]; 
 
var bgLength;// = backgrounds.length; 
 

 
var xOffset = 10; 
 
var yOffset = 67; 
 
var xPos = 0; 
 
var yPos = 0; 
 
var ssize = 40; 
 
var guide = 10; 
 
var cols = 4;//4 columns 
 

 
var selectedBackground;// = backgrounds[backgrounds.length-1];//default to last element in the list/array 
 

 
function setup(){ 
 
    createCanvas(1024, 768);noStroke(); 
 

 
    backgrounds = [color('#e8be55'), color('#ff8827'), color('#eb5051'), color('#00b4cc'), color('#005f6b'), color('#7c6753'), color('#edeaee')]; 
 
    bgLength = backgrounds.length; 
 
    selectedBackground = backgrounds[backgrounds.length-1];//default to last element in the list/array 
 
    
 
} 
 

 
function draw(){ 
 
    background(selectedBackground); 
 

 
    for(var i = 0; i < bgLength; i++) { 
 

 
    xPos = xOffset + ((i % cols) * (ssize+guide));//since % is returns the remainder of division, we use it to compute x position in the grid 
 
    yPos = yOffset + (floor(i/cols) * (ssize+guide));//and we divide by the number of columns to compute the y position in the grid 
 

 
    fill(backgrounds[i]); 
 
    //check if a box is clicked 
 
    if((mouseX >= xPos && mouseX <= xPos+ssize) && //check horizontal bounds(left/right) 
 
     (mouseY >= yPos && mouseY <= yPos+ssize)){ //check vertical bounds(top/bottom) 
 
     if(isMousePressed){//if mouse is over/within a boxes bounds and clicked 
 
      selectedBackground = backgrounds[i];//set the colour based on id 
 
     }else{//just hovering 
 
      fill(backgrounds[i].rgba[0]+50,backgrounds[i].rgba[1]+50,backgrounds[i].rgba[2]+50);//draw transparent colour, just to high light selection, not actually needed, but now an easy option 
 
     } 
 
    } 
 
    rect(xPos, yPos, ssize, ssize);//we draw at the end because the fill colour might have changed if a box was hovered 
 
    } 
 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.4.4/p5.min.js"></script>

demo preview

Смежные вопросы