Search code examples
javascripthtmlcanvaseaseljscreatejs

How to center an image on canvas with CreateJS


I'm learning CreateJS, but have run into a little struggle. Usually I'd center an image by dividing a canvas in half and subtracting half the width/height to those values, but unfortunately I don't know how to access a scaled down image's size using CreateJS.

Even using obj.image.width didn't get me anywhere, as it returns 0.

Is there any way of doing this, or some function I'm unaware of?

Massive thanks!


Solution

  • You can multiply the image size by its scale (scaleX and/or scaleY) to get the "transformed" size.

    // Note that the image must be loaded before you can get the width    
    bmp.x = (stage.canvas.width - bmp.image.width * bmp.scaleX) / 2;
    

    Here is a quick fiddle: http://jsfiddle.net/lannymcnie/v6vuwntx/