KineticJS center and scale stage with aspect fit bug
by pronebird
HTML
<script src="//cdn.jsdelivr.net/kineticjs/5.1.0/kinetic.min.js"></script>
<div id="container"></div>
CSS
body, html {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
overflow: hidden;
}
#container {
width: 100%;
height: 100%;
}
/* fix vertical-align issue on canvas */
.kineticjs-content {
display: block !important;
}
JavaScript
var Scene = {
// original dimensions of scene
baseWidth: 320,
baseHeight: 240,
stage: null,
backgroundLayer: null,
setup: function () {
// create stage
this.stage = new Kinetic.Stage({
container: "container",
width: this.baseWidth,
height: this.baseHeight
});
this.backgroundLayer = new Kinetic.Layer();
var rectShape = new Kinetic.Rect({
x: 0,
y: 0,
width: this.baseWidth,
height: this.baseHeight,
fill: 'red'
});
this.backgroundLayer.add(rectShape);
this.stage.add(this.backgroundLayer);
window.addEventListener('resize', this._callOnResize.bind(this));
this._callOnResize();
this.stage.batchDraw();
},
_callOnResize: function () {
var container = this.stage.container();
var width = container.clientWidth;
var height = container.clientHeight;
// Make sure width and height are even numbers
if(width % 2 != 0) { width--; }
if(height % 2 != 0) { height--; }
var size = {
width: width,
height: height
};
this.onResize(size);
},
onResize: function (size) {
// scale with aspect fit
var hfactor = size.width / this.baseWidth;
var vfactor = size.height / this.baseHeight;
var factor = Math.min(hfactor, vfactor);
console.log('onResize: { %f, %f }; scaleFactor = %f', size.width, size.height, factor);
// resize stage to fit new container bounds
this.stage.setSize(size);
// Layer's position is misplaced if you uncomment stage.scale()
//this.stage.scale({
// x: factor,
// y: factor
//});
// center background layer on screen
var pos = {
x: (size.width - this.baseWidth) * 0.5,
y: (size.height - this.baseHeight) * 0.5
};
// clamp
if(pos.x < 0) { pos.x = 0; }
if(pos.y < 0) { pos.y = 0;...