繁体   English   中英

通过向形状添加事件来创建画布[KineticJs]

[英]create canvas with adding events to shapes [KineticJs]

我正在尝试使用KineticJs创建绘图画布,这是jsfiddle上的代码: http : //jsfiddle.net/thekucays/k7ZMc/2/

在上面的代码中,我试图创建一个rect,并向我创建的每个单个rect添加一个事件侦听器。(第115行)

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

但是当我执行它时,如果我单击画布上的任何矩形,则该事件将在我创建的最后一个矩形上触发。.上面的代码有什么问题?

此致,Luki R Rompis

您正在使用:

 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

hy :) umm..yeah在我的代码上,我使用rect_counter的原因是我想跟踪我绘制的最后一个rect。.因此,我不需要从第一个rect开始循环以绑定事件。 。

现在我已将(在mouseup事件上)更改为:

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

现在它可以正常工作了。..到目前为止还不错..感谢您的帮助:)

最好的祝福,

鲁基·隆比斯

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM