Canvas How to - Scale to fit canvas size








Question

We would like to know how to scale to fit canvas size.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.8.3.js'></script>
<style type='text/css'>
img {<!--from   ww w.  j  ava 2s  . c o  m-->
  display: none;
}
</style>
<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){
var canvas = document.getElementsByTagName("canvas")[0],
    context = canvas.getContext("2d"),
    img = document.getElementsByTagName("img")[0];
canvas.width = 600;
canvas.height = 400;
context.drawImage(img, 0,0,600,400);
var croppedCanvas = document.getElementById("tempCanvas"),
    croppedCtx = croppedCanvas.getContext("2d");
croppedCanvas.width = 400;
croppedCanvas.height = 200;
croppedCtx.drawImage(img, 0, 0);
});//]]>  
</script>
</head>
<body>
  <h2>Original scaled to fit canvas size 600x400</h2>
  <canvas></canvas>
  <h2>Cropped Image</h2>
  <canvas id="tempCanvas"></canvas>
  <img src="http://www.java2s.com/style/download.png" />
</body>
</html>

The code above is rendered as follows: