1

With the following code, I want being logged in the console 1 2 and 3 depending on the rectangle under the pointer. What I get is always the last value, three.

I don't undestand why and how can I solve the problem.

<script src="https://unpkg.com/konva@2.4.2/konva.min.js"></script>

<div id="container"></div>
 
<script>
var stage = new Konva.Stage({
    container: 'container',
    width: 100,
    height: 100
});

var layer = new Konva.Layer();
stage.add(layer);
 
for (var i=0; i<3; ++i) {
    var rect = new Konva.Rect({
        x: 10,
        y: 30*i,
        width: 50,
        height: 20,
        fill: "red",
        stroke: "black",
        strokeWidth: 4
    });
   
    layer.add(rect);
   
    rect.on("mousemove", function() {
     console.log(i);
    });
}
   
stage.draw();

</script>
qiAlex
  • 4,290
  • 2
  • 19
  • 35
cdarwin
  • 4,141
  • 9
  • 42
  • 66

1 Answers1

1

When your mousemove event havppening, i is already and always will be 3

Try to use let i=0 instead of var i=0. with let your i variable will be in local loop scope so will be related to the layer

Code:

 var stage = new Konva.Stage({
     container: 'container',
     width: 100,
     height: 100
});

var layer = new Konva.Layer();
stage.add(layer);
 
for (let i=0; i<3; ++i) {
    var rect = new Konva.Rect({
        x: 10,
        y: 30*i,
        width: 50,
        height: 20,
        fill: "red",
        stroke: "black",
        strokeWidth: 4
    });
   
    layer.add(rect);
   
    rect.on("mousemove", function() {
     console.log(i);
    });
}
   
stage.draw();
<script src="https://unpkg.com/konva@2.4.2/konva.min.js"></script>

<div id="container"></div>

Another option is to pass i into your handler function:

var stage = new Konva.Stage({
    container: 'container',
    width: 100,
    height: 100
});

var layer = new Konva.Layer();
stage.add(layer);
 
for (var i=0; i<3; ++i) {
    var rect = new Konva.Rect({
        x: 10,
        y: 30*i,
        width: 50,
        height: 20,
        fill: "red",
        stroke: "black",
        strokeWidth: 4
    });
   
    layer.add(rect);
   
    rect.on("mousemove", (function(i) {
        return function(e) { 
            console.log(i)
        };
    })(i));
}
   
stage.draw();
<script src="https://unpkg.com/konva@2.4.2/konva.min.js"></script>

<div id="container"></div>
qiAlex
  • 4,290
  • 2
  • 19
  • 35