Search code examples
javascripthtmlcanvaskineticjs

KineticJS: How do I get the Width and Height of a Sprite or Image?


I loaded a sprite from a URL and wanted to get the width and height of the sprite it turns out that the width and height is alway zero. I created the following example.

How do I get the real width and height of the sprite?

I use the sprite example and created a jsfiddle here: http://jsfiddle.net/confile/jVG9t/

This is the html code:

<div id="container"></div>
    <div id="buttons">
      <input type="button" id="punch" value="Width">
    </div>
    <script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v5.1.0.min.js"></script>


Image <br>
<div id="mydiv" ></div>        

This is the JS code:

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: [
              // x, y, width, height (4 frames)
              2,2,70,119,
              71,2,74,119,
              146,2,81,119,
              226,2,76,119
            ],
            punch: [
              // x, y, width, height (3 frames)
              2,138,74,122,
              76,138,84,122,
              346,138,120,122
            ]
          },
          frameRate: 7,
          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();

        var frameCount = 0;

        blob.on('frameIndexChange', function(evt) {
          if (blob.animation() === 'punch' && ++frameCount > 3) {
            blob.animation('idle');
            frameCount = 0;
          }
        });

        document.getElementById('punch').addEventListener('click', function() {
            alert("blob.width: "+blob.width());

        }, false);
      };
      imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/blob-sprite.png';

Solution

  • You can get the width/height of the whole imageObj by requesting its .width & .height properties:

    var imageObj = new Image();
    imageObj.onload = function() {
        var width=imageObj.width;
        var height=imageObj.height;
    }
    

    If the imageObj is a spritesheet then there is no way to programatically get the x, y, width, height of the individual sprites on that spritesheet. Often the spritesheet author will give you this information. You can often eyeball the spritesheet and see how its laid out.

    Your KineticJS demo required the coder to know where the x,y,width,height of each sprite on the spritesheet.