0

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!

Vinny
  • 309
  • 3
  • 11

1 Answers1

1

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/

lavrton
  • 18,973
  • 4
  • 30
  • 63
  • Awesome thanks a lot! Just a couple questions to help me understand better 1. why do I need to create closure for the x variable 2. whats the difference between target and targetNode? – Vinny Aug 21 '14 at 12:48
  • 1
    You need to use closure because `sceneFunc` will call at every draw. But after `for` loop `x` variable will = 150, it is same value for all shapes. Look here for more info: http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – lavrton Aug 21 '14 at 13:17
  • `targetNode` is deprecated. `target` for newer versions. – lavrton Aug 21 '14 at 13:18