Skip to content

Instantly share code, notes, and snippets.

@superguigui
Created October 29, 2012 11:37
Show Gist options
  • Save superguigui/3973091 to your computer and use it in GitHub Desktop.
Save superguigui/3973091 to your computer and use it in GitHub Desktop.
Fit image/content to your window so that the ratio is respected and your image is moved to the center.
// FIT INTO SCREEN
// Your image or content size
var contentWidth = 1024;
var contentHeight= 768;
// The resize function, to be impletemented however you need it
function resize(){
var w, h, ws, hs, rs, rc, r;
// get size of the screen
ws = window.innerWidth;
hs = window.innerHeight;
// calculates ratios of screen and content
rs = ws / hs;
rc = contentWidth / contentHeight;
// we chose the correct ratio
if(rs > rc){
r = ws / contentWidth;
}
else{
r = hs / contentHeight;
}
// get new width and height
w = contentWidth * r;
h = contentHeight * r;
// Here it's up to you to either set the scaleX and scaleY of your content to "r"
// or the width and height to w and h
// Also to move your content to the center :
// content.x = (ws >> 1) - (w >> 1);
// content.y = (hs >> 1) - (h >> 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment