convergedtarkus
convergedtarkus

Reputation: 697

KineticJS how animate an image

I'm trying to animate an image using KineticJS to move across the screen, but I keep getting not a function errors. The image displays fine, but it keeps saying that imageObj.move is not a function and I have no idea why. I'm kinda new to javascript and KineticJS, so I could just be making a really basic error, so some help would be very welcome. Thanks!

window.onload = function(){ //init function
var stage = new Kinetic.Stage("container", 600, 600);
var fluffyImgLayer = new Kinetic.Layer();

var imageObj = new Image();
imageObj.onload = function(){
    imageF = new Kinetic.Image({
        x: 0,
        y: 250,
        image: imageObj,
    });

    fluffyImgLayer.add(imageF);

    stage.add(fluffyImgLayer);
    }

    imageObj.src = "Flutter_Fluffy_100.png";

    stage.onFrame(function(frame){
        console.log("fired")
        imageObj.move(10,10);
        fluffyImgLayer.draw();
    });

    var period = 2000;

    stage.start();
}

Upvotes: 1

Views: 5229

Answers (2)

Eric Rowell
Eric Rowell

Reputation: 5219

Actually, to answer your question, the problem is that you're trying to use a KineticJS method on the image object (rather than the Kinetic.Image object). Use this instead:

imageF.move(10,10);

Upvotes: 4

randompast
randompast

Reputation: 693

You could do something like this and be done with it:

imageObj.x += 3;
imageObj.y += 3;

You need to add var in front of imageF:

var imageF = new Kinetic.image({

Take a look at: http://www.html5canvastutorials.com/kineticjs/html5-canvas-kineticjs-image-tutorial/

The error your getting is because you didn't define move() anywhere. You could make a move function and allow the object to use it. Or, you could make a function like this:

function moveMyThing(myObj, xchange, ychange)
{
  myObj.x += xchange;
  myObj.y += ychange;
}

Then call it with:

moveMyThing(imageObj, 3, 3);

KineticJS tends to refresh around 60FPS if all is alright, so this 3 is actually quite fast. You'll also want to consider checking whether or not it is time to update your movement logic. It'd be best to uncouple them.

Ex:

stage.onFrame(function(frame){
    console.log("fired")
    time++;
    if(readyToThink(time, 6)) //check if you want to do something 
      moveMyThing(imageObj,3,3); //Then move it...
    fluffyImgLayer.draw();
});

function readyToThink(time, limit){
  if(time > limit) //some amount of time to get here
  {
    time = 0; //reset counter
    return true;
  }
  return false;
}

To account for the jumpiness, you can tween the motion.

Upvotes: 1

Related Questions