var container = document.getElementById('container');
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
// this function fill an image on canvas
function drawImage(image) {
context.drawImage(image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height);
}
var imageObj = new Image();
imageObj.onload = function () {
drawImage(this);
};
imageObj.src = "https://dl.dropboxusercontent.com/u/37981960/images/stackoverflow/wally.jpg";
// set this to false to maintain the canvas aspect ratio, or true otherwise
var stretch_to_fit = false;
function resize() {
// aspect ratio
var widthToHeight = canvas.width / canvas.height;
var newWidthToHeight = widthToHeight;
// cache the window dimensions (discount the border)
var newWidth = window.innerWidth,
newHeight = window.innerHeight;
if (stretch_to_fit) {
// overwrite the current canvas aspect ratio to fit the entire screen
widthToHeight = window.innerWidth / window.innerHeight;
} else {
newWidthToHeight = newWidth / newHeight;
}
// scale the container using CSS
if (newWidthToHeight > widthToHeight) {
newWidth = newHeight * widthToHeight;
container.style.height = newHeight + 'px';
container.style.width = newWidth + 'px';
} else {
newHeight = newWidth / widthToHeight;
container.style.width = newWidth + 'px';
container.style.height = newHeight + 'px';
}
// adjust the container position
// (a visual sugar that centralises the canvas on result page)
container.style.marginTop = (-newHeight / 2) + 'px';
container.style.marginLeft = (-newWidth / 2) + 'px';
};
// listen to resize events
window.addEventListener('resize', function () {
resize();
}, false);
// also resize the screen on...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.