i'm trying to create a drawing canvas using KineticJs, here's the code on jsfiddle : http://jsfiddle.net/thekucays/k7ZMc/2/
on my code above, i'm trying to create a rect, and add an event listener to every single rect i created.. (line 115)
var item = layer.get('.rect1');
item.on('click', function(){
item.setFill('RED');
});
but when i execute it, if i click any rect on the canvas, the event fires on the last rect i created.. what's wrong with my code above?
best regards, Luki R Rompis
you were using:
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');
});
try a more basic workaround: -------- This one works best for me -----------
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');
});
}
};
or simply try just using:
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 on my code, the reason why i used rect_counter is that i want to track the last rect i drawed..so i don't need to start over the loop from the first rect to bind the event..
now i have changed (on the mouseup event) into :
var rects = stage.get('.rect'+rect_counter);
rects.on('click', function(){
this.setAttrs({
fill: 'red'
});
//layer.draw();
});
now it works..and so far so good..thanks for your help :)
best regards,
Luki R Rompis
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.