Skip to content

Instantly share code, notes, and snippets.

@psbolden
Created May 26, 2017 15:28
Show Gist options
  • Save psbolden/978f55f2beac71f6d9b68bdeeab10ecb to your computer and use it in GitHub Desktop.
Save psbolden/978f55f2beac71f6d9b68bdeeab10ecb to your computer and use it in GitHub Desktop.
Scale Image to fit on canvas
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<canvas id='cv'></canvas>
<button id='other'>other image</button>
</body>
</html>
//Source: https://stackoverflow.com/questions/23104582/scaling-an-image-to-fit-on-canvas
var canvas=document.getElementById('cv');
var ctx= canvas.getContext('2d');
var img = new Image();
img.onload= drawImageScaled.bind(null, img, ctx);
function drawImageScaled(img, ctx) {
var canvas = ctx.canvas ;
var hRatio = canvas.width / img.width ;
var vRatio = canvas.height / img.height ;
var ratio = Math.min ( hRatio, vRatio );
var centerShift_x = ( canvas.width - img.width*ratio ) / 2;
var centerShift_y = ( canvas.height - img.height*ratio ) / 2;
ctx.clearRect(0,0,canvas.width, canvas.height);
ctx.drawImage(img, 0,0, img.width, img.height,
centerShift_x,centerShift_y,img.width*ratio, img.height*ratio);
}
img.src = 'http://s1.dmcdn.net/BhdSy/526x297-KuG.jpg';
document.getElementById('other').onclick = function() {
img = new Image();
img.onload= drawImageScaled.bind(null, img, ctx);
img.src =
'http://www.pliagedepapier.com/gallery/albums/userpics/12780/DogEvie-JasonKuG.jpg';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment