【问题标题】:Cannot read property 'rotation' of undefined kineticjs无法读取未定义 kineticjs 的属性“旋转”
【发布时间】:2014-08-21 13:58:42
【问题描述】:

过去一个小时我一直盯着这个看,无法弄清楚。

我正在尝试使用 KineticJS 在单击时将形状旋转 45 度。我从 Stack Overflow 上的上一个问题中找到了http://jsfiddle.net/JUu2Q/6/,它基本上可以满足我的需求。当我将此应用于我的代码(并将“层”更改为“阶段”)时,出现以下错误:无法读取未定义的属性“旋转”:

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();
      }); 

我确定我做错了什么,但我就是想不通。

我的代码可以在http://jsfiddle.net/0h55fdzL/找到

我只使用 KineticJS 几个小时,如果这是个愚蠢的问题,我深表歉意

感谢您的帮助!

【问题讨论】:

    标签: javascript html kineticjs


    【解决方案1】:

    1 为x 变量创建闭包。

    2 使用target 而不是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/

    【讨论】:

    • 非常感谢!只是几个问题可以帮助我更好地理解 1. 为什么我需要为 x 变量创建闭包 2. target 和 targetNode 之间有什么区别?
    • 您需要使用闭包,因为sceneFunc 将在每次抽奖时调用。但在for 循环x 变量将= 150 之后,所有形状的值都相同。在这里查看更多信息:stackoverflow.com/questions/750486/…
    • targetNode 已弃用。 target 更新版本。
    猜你喜欢
    • 2017-01-07
    • 1970-01-01
    • 1970-01-01
    • 2013-06-16
    • 2013-02-09
    • 1970-01-01
    • 1970-01-01
    • 2022-10-20
    • 2020-04-06
    相关资源
    最近更新 更多