1

KineticJsを使用して描画キャンバスを作成しようとしています。jsfiddleのコードは次のとおりです:http: //jsfiddle.net/thekucays/k7ZMc/2/

上記のコードでは、rectを作成し、作成したすべてのrectにイベントリスナーを追加しようとしています。(115行目)

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

しかし、それを実行するときに、キャンバス上の任意のrectをクリックすると、最後に作成したrectでイベントが発生します。上記のコードの何が問題になっていますか?

よろしく、ルキRロンピス

4

2 に答える 2

0

hy :)うーん..ええ、私のコードでrect_counterを使用した理由は、描画した最後のrectを追跡したいからです。したがって、イベントをバインドするために最初のrectからループを最初からやり直す必要はありません。 。

今、私は(mouseupイベントで)次のように変更しました:

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

今それは動作します..そしてこれまでのところとても良い..あなたの助けに感謝します:)

よろしくお願いします、

ルキRロンピス

于 2013-01-21T17:06:02.947 に答える
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
于 2013-01-21T15:29:59.557 に答える