Skip to content

Instantly share code, notes, and snippets.

@sdaityari
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sdaityari/abfb051e759519c7cd48 to your computer and use it in GitHub Desktop.
Save sdaityari/abfb051e759519c7cd48 to your computer and use it in GitHub Desktop.

Basic Animation Using Kinetic Sprite

Kinetic Sprite is one the easiest way to show animation on a webpage. For the newbies, KineticJS is a 2D canvas library. Canvas is an HTML5 element used to draw pictures. The KineticJS Library is an easy-to-go API to the cumbersome canvas library and has definitely simplified the tasks.

The detailed documentation of Kineticjs is definitely a good source to pick up things. In this tutorial, we are going to do little animation. It will comprise of a simple circle moving around a rectangle. Although this simple looking example can enable you to the vast capabilities of the library.

Pre-requisites

Basic knowledge of Javascript, namespaces and a little of KineticJS. Grabbing Kinetic is very easy. There are various tutorials available but start with a basic one

Introduction to Kinetic Sprite

KineticJS requires a "Stage" and a "Layer" to initialize all Kinetic objects. They are basically two classes that need to to be used for animations.

Kinetic Sprite is an animation library and part of KineticJS. It allows the basic animation via image flipping method. The endpoint images are to be defined, rest is controlled by framerate and Sprite.

Image

So first of all we need an image which will show all the positions of the circle. The rectangle will have to be of same size but the circle at different positions. I am going to use the following image in the code.

Rectangle to be used for Sprite Animation

It consists of 4 rectangles with different circle positions. Each rectangle is 221px wide and 146px in height. Only the circle position is changed in each.

Start Coding

Finalizing of the image allows us to finally code it down. We start with the basic HTML tags or bootstrapping the page.

<html>
<head>
    <style>
      body {
        margin: 0px;
        padding: 0px;
      }
      #container {
        background-color: #222;
        display: inline-block;
        width: 580px;
        height: 202px;
      }
    </style>
</head>

Next, the <body> is added with a div and script tag to load the kinetic library.

<body>
    <div id="container"></div>
    <script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v5.0.1.min.js"></script>

Thereafter, we add a <script> tag with a defer as true. This allows that part to run only after the whole page loads completely. Also, we declare the new Kinetic Stage and Layer to initiate the project.

<script defer="defer">
      var stage = new Kinetic.Stage({
        container: 'container',
        width: 578,
        height: 200
      });
      var layer = new Kinetic.Layer();

The above code declares a new stage of width 578px and height 200px. Also, its context has been attached to <div id='container'>. It means that div will be display the animation we are going to make. The new Layer is just to add objects to stage. Next, we add a Kinetic Image object and a Kinetic Sprite object. We use the onload functionality in image and initiate the Kinetic Sprite object after it gets loaded.

var imageObj = new Image();
imageObj.onload = function() {
    var blob = new Kinetic.Sprite({
        x: 250,
        y: 40,
        image: imageObj,

First of all we create a Kientic Image object called imageObj.

x specifies the x coordinate and y for y coordinate. image specifies the Image Object we are going to use. Here it is imageObj we just created. Next we move onto define animation part. It consists of 2 objects.

  • animation : To specify the animation name array we are going to use.
  • animations : To describe the exact animation we are going to perform.

It is specified using 4 parameter system.

  • First is x specifying the top left x coordinate of the image to be displayed (pixel wise).
  • Followed by the y coordinate.
  • Then comes the width of the image to be shown.
  • Followed by height.

In our image, we made 221 pixels wide rectangle of height 146px. Since we want to start our animation from the first image, the first set of parameters come to be

[0,0,221,146,..
  • 0,0 specify the top left corner.
  • 221,146 the width and height.

Our frame width is constant. Hence 221,146 will never change. Also our images are horizontal which means the y coordinate will also not change. Now to move the circle to desired position, we move to our next image accordingly specifying the particular position.

When we move to our next image ie to the right, only x coordinate changes. Adding the width (by common sense) will take you to next rectangle. Hence our next coordinate can be like:

[441,0,221,146,..

In this way we define our animation pattern. So the full code for Kinetic Sprite object is

imageObj.onload = function() {
        var blob = new Kinetic.Sprite({
          x: 250,
          y: 40,
          image: imageObj,
          animation: 'idle',
          animations: {
            idle: [
              0,0,221,146,
              221,0,221,146,
              441,0,221,146,
              661,0,221,146,
              441,0,221,146,
              661,0,221,146,
              883,0,221,146,
              441,0,221,146,
              661,0,221,146,
              441,0,221,146,
              661,0,221,146,
              0,0,221,146,
            ]
          },
          frameRate: 5,
          frameIndex: 0
        });

Notice the animations section and the value of idle array. There is a list of specified locations showing a random movement of circle throughout the animation.

We specify the frameRate as 5 ie the number of frames to be displayed per second and frameIndex as 0 ie to start the animation from first frame. Next we specify the imageObj source so that our desired image loads. Now we simply need to add this to layer and in turn to stage and start the animation. So the full code is as follows (self explanatory):

<script defer="defer">
      var stage = new Kinetic.Stage({
        container: 'container',
        width: 578,
        height: 200
      });
      var layer = new Kinetic.Layer();

      var imageObj = new Image();
      imageObj.onload = function() {
        var blob = new Kinetic.Sprite({
          x: 250,
          y: 40,
          image: imageObj,
          animation: 'idle',
          animations: {
            idle: [
              0,0,221,146,
              221,0,221,146,
              441,0,221,146,
              661,0,221,146,
              441,0,221,146,
              661,0,221,146,
              883,0,221,146,
              441,0,221,146,
              661,0,221,146,
              441,0,221,146,
              661,0,221,146,
              0,0,221,146,
            ]
          },
          frameRate: 5,
          frameIndex: 0
        });

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

        // add the layer to the stage
        stage.add(layer);

        // start sprite animation
        blob.start();
      };
      imageObj.src = 'untitled.png';
</script>

I have the image in my root folder. The image route must be specified as per the image location.

Thats all we needed to make it animate. Vary the frameRate and 'idle' variable to experiment. Modification of image with more positions will also help.

The complete code lies at github:kinetic-sprite

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment