Search code examples
javascriptjqueryimagekineticjstween

Kinetic.js not tweening image at all, not sure what Im doing incorrectly


Im just trying to have the image tween slowly to the left. As far as I can tell, the code is correct. The image loads, but there is no motion.

  var stage = new Kinetic.Stage({
    container: 'container',
    width: 1920,
    height: 1080
  });
  var layer = new Kinetic.Layer();

  var imageObj = new Image();
  imageObj.onload = function() {
    var space = new Kinetic.Image({
      x: 0,
      y: 0,
      image: imageObj,
      width: 1920,
      height: 1080
    });

    // add the shape to the layer
    layer.add(space);

    // add the layer to the stage
    stage.add(layer);
  };
  imageObj.src = 'http://farm4.staticflickr.com/3768/11633218256_30a04f01c3_o.png';
  var tween = new Kinetic.Tween({
    node: space, 
    duration: 20,
    x: -1920,
    y: 0,
  });
  setTimeout(function() {
    tween.play();
  }, 2000);

Solution

  • A few scoping problems with the code:

    • Make sure your space and tween variables are in scope (currently hidden in .onload)
    • Since the image will take time to load, you should start the tween in imageObj.onload

    Here's code and a Demo: http://jsfiddle.net/m1erickson/JT2cD/

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title>Prototype</title>
        <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
        <script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.7.2.min.js"></script>
    
    <style>
    body{padding:20px;}
    #container{
      border:solid 1px #ccc;
      margin-top: 10px;
      width:500px;
      height:500px;
    }
    </style>        
    <script>
    $(function(){
    
        var stage = new Kinetic.Stage({
            container: 'container',
            width: 500,
            height: 500
        });
        var layer = new Kinetic.Layer();
        stage.add(layer);
    
        var space;
        var tween;
    
        var imageObj = new Image();
        imageObj.onload = function() {
          space = new Kinetic.Image({
            x: 0,
            y: 0,
            image: imageObj,
            width: 1920/4,
            height: 1080/4
          });
    
          // add the shape to the layer
          layer.add(space);
    
          // add the layer to the stage
          stage.add(layer);
    
          tween = new Kinetic.Tween({
            node: space, 
            duration: 20,
            x: -1920/4,
            y: 0,
          });
    
          setTimeout(function(){ tween.play(); }, 2000);
    
        };
        imageObj.src = 'http://farm4.staticflickr.com/3768/11633218256_30a04f01c3_o.png';
    
    }); // end $(function(){});
    
    </script>       
    </head>
    <body>
        <div id="container"></div>
    </body>
    </html>