KineticJS - Scaling stage to viewport

2020-06-27 09:06发布

问题:

I'm working towards a default resolution of 1366x756.

I would to scale this up and down depending on the viewport. Similar to the example shown here: http://blogs.msdn.com/b/davrous/archive/2012/04/06/modernizing-your-html5-canvas-games-with-offline-apis-file-apis-css3-amp-hardware-scaling.aspx

I'm kind of confused how I would get this to work in KineticJS as it abstracts away the canvas elements used.


What I would like to achieve is basically:

window.addEventListener("resize", OnResizeCalled, false);

function OnResizeCalled() {
    canvas.style.width = window.innerWidth + 'px';
    canvas.style.height = window.innerHeight + 'px';
}

I know that this isn't the perfect solution as this would stretch the canvas and not keep aspect ratio.


I'm currently using the following:

stage.setWidth(window.innerWidth);
stage.setHeight(window.innerHeight);
stage.setScale(window.innerWidth / 1366)

It's more or less what I'm looking for, but:

  • mouse/touch actions aren't scaled to the new proportions.

  • not the native scaling which uses the GPU to upscale the canvas object.


Any ideas? Thanks :)

回答1:

On a separate problem I was trying to help solve, the user him/herself (user848039) figured out a solution that dealt with mouse position and KineticJS scaling.

This was the question: kineticjs stage.getAbsoluteMousePosition()?.

Credits go to him, but here was his formula that I modified to meet a more common KineticJS setup:

var mousePos = stage.getMousePosition();

mousePos.x = mousePos.x/stage.getScale().x-stage.getAbsolutePosition().x/stage.getScale().x+stage.getOffset().x;
mousePos.y = mousePos.y/stage.getScale().y-stage.getAbsolutePosition().y/stage.getScale().y+stage.getOffset().y;

Perhaps jsFiddle isn't the best example for this, since you want the stage to be innerWidth and innerHeight. Those measurements seem to play a bit weird in the jsFiddle frame, but if you look at the code, you'll see that I set the stage exactly the same as you mentioned above. With the new calculations for mousePos the mousePos.x and mousePos.y are returning the proper coordinates for your scale.