Created
March 14, 2011 10:58
-
-
Save fnordfish/868996 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* jQuery is needed for calculating screen-size and events only! | |
* this is a stub only! | |
* assumes <canvas id="screen"> | |
*/ | |
jQuery.noConflict(); | |
jQuery(document).ready(function (j) | |
{ | |
var currentImage; | |
var screenCanvas = document.getElementById('screen'); | |
var ctx = screenCanvas.getContext('2d'); | |
var initScreen = function () { | |
var w = j(window); | |
screenCanvas.height = w.height(); | |
screenCanvas.width = w.width(); | |
// console.log("Canvas is: " + screenCanvas.width + " x " + screenCanvas.height); | |
}; | |
initScreen(); | |
var drawImage = function () { | |
var sourceX = 0, | |
sourceY = 0, | |
sourceWidth = currentImage.width, | |
sourceHeight = currentImage.height, | |
destX = 0, | |
destY = 0, | |
canvasWidth = screenCanvas.width, | |
canvasHeight = screenCanvas.height; | |
// console.log('Image is: ' + sourceWidth +' x '+ sourceHeight); | |
var scale = Math.max( canvasWidth/sourceWidth, canvasHeight/sourceHeight ); | |
var scaled_width = sourceWidth * scale, | |
scaled_height = sourceHeight * scale; | |
// console.log('Scaled is: '+ scale + " -> " + scaled_width +' x '+ scaled_height); | |
if (scaled_height > canvasHeight) | |
{ | |
sourceY = Math.floor( Math.abs((scaled_height - canvasHeight) / 2) / scale ); | |
sourceHeight = sourceHeight - 2 * sourceY; | |
} | |
if (scaled_width > canvasWidth) | |
{ | |
sourceX = Math.floor( Math.abs((scaled_width - canvasWidth) / 2) / scale ); | |
sourceWidth = sourceWidth - 2 * sourceX; | |
} | |
// drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh) | |
// console.log('sx:'+sourceX, 'sy:'+sourceY, 'sw:'+sourceWidth, 'sh:'+sourceHeight, | |
// 'dx:'+destX, 'dy:'+destY, 'dw:'+canvasWidth, 'dh:'+canvasHeight); | |
ctx.drawImage(currentImage, | |
sourceX, sourceY, sourceWidth, sourceHeight, | |
destX, destY, canvasWidth, canvasHeight); | |
}; | |
currentImage = new Image(); | |
currentImage.onload = function (e, e2) { | |
drawImage(); | |
}; | |
currentImage.src = "someImage.jpg"; | |
j(window).resize(/*eventData,*/ function (evt) { | |
initScreen(); | |
drawImage(); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment