Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save fnordfish/868996 to your computer and use it in GitHub Desktop.
Save fnordfish/868996 to your computer and use it in GitHub Desktop.
/**
* 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