Search code examples
javascriptcanvasbitmapcreatejseaseljs

Why does Bitmap.scale not work?


I want to add my image to a canvas, and position and scale it. I know how to position it, but every time I scale it, it disappears from my canvas.

My current code looks similar to this:

function init() {
    var canvas = new createjs.Stage("canvas");

    var image = new createjs.Bitmap("assets/image.png");
    image.scale(600, 600);
    canvas.addChild(image);
    canvas.update(image);
}

My image does not appear on the canvas unless I remove image.scale(600, 600).


Solution

  • According to the documentation, the scale property is the scale factor. For example, a scale of 2 means that the image is two times as large. You're making the image 600 times as large. So a 64x64px image would become a 38400x38400px image. You'll need to calculate the factor from the image's dimensions:

    const imageBounds = image.getBounds()
    image.scaleX = 600 / imageBounds.width;
    image.scaleY = 600 / imageBounds.height;
    

    Notice also that scale is a property, you can also directly assign to it:

    image.scale = 1.6;