0
votes

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/

1
Can you create any jsfiddle?lavrton
@lavrton I've updated the post with jsfiddle link. Uncomment stage.scale to see how it works with scaling. Maybe I don't get something, but I expected coordinates being mapped to canvas dimensions when scaling used.Rob Zombie
@lavrton any thoughts on this issue? I've checked with master, same issue. Am I doing something wrong?Rob Zombie
What are you expecting? Why you need to change position of layer? Where react shoud be placed, in center?lavrton
@lavrton I am tryng to achieve a proportional scaling of the whole stage to fit viewport or container div. Because the stage itself can be of any size, I have to center layer inside. For example, with aspect ratio of 4:3, I would have to center layer vertically on screen. All of this works fine until I turn on scaling. If I stop centring content and stick it at {0,0}, then it works fine but leaves empty space below the layer.Rob Zombie

1 Answers

0
votes

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.