2013-01-21 43 views
1

我想要創建一個使用KineticJs繪圖畫布,這裏的一對的jsfiddle代碼: http://jsfiddle.net/thekucays/k7ZMc/2/創建畫布添加事件,形狀[KineticJs]

上面我的代碼

,我試圖創建一個矩形和事件監聽器添加到每一個矩形我創建..(115線)

var item = layer.get('.rect1'); 
item.on('click', function(){ 
    item.setFill('RED'); 
}); 

但是當我執行它,如果我點擊畫布上的任何矩形,在矩形最後事件觸發我創建。 。 上面的代碼有什麼問題?

最好的問候, 盧基[R Rompis

+0

你的jsfiddle不起作用,因爲你沒有對kinetic.js和kode.js的引用 – SoluableNonagon

回答

0

你使用:

var item = layer.get('.rect1'+rect_counter); //dont user "+rec_counter" as this is what binds it to the LAST element 
item.on('click', function(){ 
    item.setFill('RED'); 
}); 

嘗試一個更基本的解決辦法:--------這一個最適合我---- -------

var itemsList = layer.getChildren(); //gets all shapes in this layer 
for(var i=0; i<itemsList.length; i++){ 
     if(itemsList.getName == 'rect1'){ //since you named your rectangles 'rect1' check name 
      itemsList[i].on('click', function(){ 
      item.setFill('RED'); 
      }); 
     } 
}; 

或簡單地嘗試只使用:

var item = layer.get('.rect'); //all rectangles, without number 
item.on('click', function(e){ // I think you need an 'e' here 
    item.setFill('RED'); 
}); 
// I doubt this will work as ALL your rectangles need to have the same name if you want to .get() them all 
0

hy :) umm..yeah在我的代碼中,我之所以使用rect_counter的原因是,我想追蹤最後一個矩形,我繪製..所以我不需要從第一個矩形的循環開始綁定事件..

現在我已經改變(在鼠標鬆開事件)爲:

var rects = stage.get('.rect'+rect_counter); 
rects.on('click', function(){ 
    this.setAttrs({ 
     fill: 'red' 
    }); 
    //layer.draw(); 
}); 

現在works..and到目前爲止good..thanks您的幫助:)

最好問候,

Luki R Rompis