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 - 2,
newHeight = window.innerHeight - 2;
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 canvas
if (newWidthToHeight > widthToHeight) {
newWidth = newHeight * widthToHeight;
canvas.height = newHeight;
canvas.width = newWidth;
} else {
newHeight = newWidth / widthToHeight;
canvas.width = newWidth;
canvas.height = newHeight;
}
};
// listen to resize events
window.addEventListener('resize', function () {
// resizes the canvas (this will clear the canvas because the width and height parameters are changed).
resize();
// so, we need to redraw the image back on canvas
drawImage(imageObj);
}, false);
// also resize the screen on orientation changes
window.addEventListener('orientationchange', function () {
resize();
...
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.