Search code examples
javascripthtmlkineticjs

Cannot read property 'rotation' of undefined kineticjs


I've been staring at this for the past hour and cannot figure it out.

I'm trying to use KineticJS to rotate a shape 45 degrees when it is clicked. I found http://jsfiddle.net/JUu2Q/6/ from a previous question on Stack Overflow which does basically what I want. When I apply this to my code (and change 'layer' to 'stage'), I get the following error: Cannot read property 'rotation' of undefined:

layer.on('click tap', function(evt) {
          evt.targetNode.tween = new Kinetic.Tween({
              node: evt.targetNode,
              duration: 0.3,
              rotationDeg: evt.targetNode.rotation()+45,
              easing: Kinetic.Easings.EaseOut
          });
          evt.targetNode.tween.play();
      }); 

I'm sure I'm doing something wrong but I just can't figure it out.

My code can be found at http://jsfiddle.net/0h55fdzL/

I've only be using KineticJS for a few hours so I apologize if this is stupid question

Thanks for your help!


Solution

  • 1 Create closure for x variable.

    2 Use target instead of targetNode

    var x = -50;
    var y = -50;
    
    var stage = new Kinetic.Stage({
      container: 'container',
      width: 1200,
      height: 1200,
    });
    
    for (i=0; i<3; i++){
      x = x + 50;
      y = y + 50;
    
      var layer = [];
      layer[i] = new Kinetic.Layer();
    
      var hex = [];
      (function(x){
        hex[i] = new Kinetic.Shape({
          sceneFunc: function(context) {
            context.beginPath();
            context.moveTo(x+25, 0);
            context.lineTo(x+40, 10);
            context.lineTo(x+40, 25);
            context.lineTo(x+25, 35);
            context.lineTo(x+10, 25);
            context.lineTo(x+10, 10);
            context.closePath();
            // KineticJS specific context method
            context.fillStrokeShape(this);
          },
          fill: '#00D2FF',
          stroke: 'black',
          strokeWidth: 4,
          draggable: true,
          rotation:0
        });
      })(x);
    
    
    
      // add the triangle shape to the layer
      layer[i].add(hex[i]);
      // add the layer to the stage
      stage.add(layer[i]);
    }
    
    
    stage.on('click tap', function(evt) {
        evt.target.tween = new Kinetic.Tween({
            node: evt.target,
            duration: 0.3,
            rotationDeg: evt.target.rotation()+45,
            easing: Kinetic.Easings.EaseOut
        });
        evt.target.tween.play();
    });
    

    http://jsfiddle.net/0h55fdzL/1/