0

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/

6
  • Can you create any jsfiddle?
    – lavrton
    Sep 3, 2014 at 0:46
  • @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.
    – pronebird
    Sep 3, 2014 at 10:40
  • @lavrton any thoughts on this issue? I've checked with master, same issue. Am I doing something wrong?
    – pronebird
    Sep 15, 2014 at 10:44
  • What are you expecting? Why you need to change position of layer? Where react shoud be placed, in center?
    – lavrton
    Sep 16, 2014 at 2:57
  • @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.
    – pronebird
    Sep 16, 2014 at 9:22

1 Answer 1

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.