Search code examples
javascriptkineticjs

Centering layer in scaled stage


I work in fixed coordinate space, let's say {x:0, y:0, w:800, h:600}. Canvas is scaled to fit the window dimensions, then I scale the stage and redraw it. Then I center my background layer within stage. If I don't use scaling of the entire stage, then centering works fine, however when I set scale for stage, calculated coordinates do not match what I see on screen.

What's is the trick with stage scaling and how to position layer then?

// @param size window size {width, height}
MyScene.prototype.scaleAndCenterScene = function (size) {
    var hfactor = size.width / this.baseWidth;
    var vfactor = size.height / this.baseHeight;
    var factor = Math.min(hfactor, vfactor);

    // resize stage
    this.stage.setSize(size);

    // scale stage
    this.stage.setScale({
        x: factor,
        y: factor
    });

    // calculate center
    var pos = {
        x: (size.width - this.baseWidth) * 0.5,
        y: (size.height - this.baseHeight) * 0.5
    };
    // center layer
    this.backgroundLayer.position(pos);

    // redraw
    this.stage.batchDraw();
};

JSFiddle is available at: http://jsfiddle.net/pronebird/ahqa9a3y/


Solution

  • The key was to use stage.scale combined with stage.position, plus couple of tricks to handle absolute and fixed coordinate spaces. I wrote a blog post on this: https://coderwall.com/p/dy_dla.