How to resize the kinetic canvas and maintain the aspect ratio

First of all, credit goes to the original aspect ratio code here which was built to deal with aspect ratio of images but it can still be used for scaling canvas too. If you need to see it in action, then try resizing your browser window whilst playing this game I've built before which uses this function. The following example is based on that the stage is called 'stage' and by default the canvas size is at 720px (width) x 440px (height). Without further a do, here is the code:

 

function scaleStageForMobile() {
/* Resize for mobile phones START */

if ((window.innerWidth <= 1000))
{

var maxWidth = window.innerWidth; // Max width for the image
var maxHeight = window.innerHeight; // Max height for the image
var ratio = 0; // Used for aspect ratio
var width = 720; // Current image width
var height = 440; // Current image height

// Check if the current width is larger than the max
if(width > maxWidth){
ratio = maxWidth / width; // get ratio for scaling image
var newWidth = maxWidth;
var newHeight = height * ratio;
stage.setWidth(newWidth);
stage.setHeight(newHeight);
height = height * ratio; // Reset height to match scaled image
width = width * ratio; // Reset width to match scaled image
}

// Check if current height is larger than max
if(height > maxHeight){
ratio = maxHeight / height; // get ratio for scaling image
var newHeight = maxHeight;
var newWidth = width * ratio;
stage.setWidth(newWidth);
stage.setHeight(newHeight);
width = width * ratio; // Reset width to match scaled image
}


var scaleXValue = newWidth / 720;
var scaleYValue = newHeight / 440;


stage.scaleX(scaleXValue); /* This is always new canvas width / old canvas width */
stage.scaleY(scaleYValue); /* This is always new canvas height / old canvas height */

stage.draw(); /* Needed when flipping orientation in mobile devices */
}
else
{
stage.setWidth(720);
stage.setHeight(440);

stage.scaleX(1);
stage.scaleY(1);

stage.draw(); /* Needed when flipping orientation in mobile devices */
}

/* Resize for mobile phones END */
};

 

Like It? Share It!

 

Leave a comment

 

Need help with this article?

Have you got a suggestion, compliment or need additional help with this article? Simply contact me at ajfhoward[@t]hotmail.com and I'll try to help as much as I can.