Falcon80 Logo
Clipping an image and scaling it

The drawImage() method is very powerful in terms of manipulating an image. In addition to scaling an entire image, you can also clip a specific area and scale it to the desired width and height. This feature is esepcially useful if you have to focus attention to a particular area within an image.

For example, you can clip a single dove from the image below and scale it as shown on the side.
To clip and scale the image, the drawImage has to be fed 9 parameters.

drawImage(Image, clipStartX, clipStartY, clipWidth, clipHeight, x coordinate, y coordinate, scaleWidth, scaleHeight)

The drawImage method takes 'Image', and clips an area. The clipping area is specified by clipStartX, clipStartY, clipWidth and clipHeight (In the above image, the area covered by the red square is the clipping area). (x coordinate, y coordinate) is the point at which the final image will be placed. scaleWidth and scaleHeight specify the width and height of the scaled image (see clipped image on the right).

Note that the width and height are in pixels.
HTML Code
<html>
<head>
  <script type="application/javascript">
function init() {
var canvas = document.getElementById("canvas");
if (canvas.getContext)
{
var ctx = canvas.getContext("2d");

// Create a new image object
var dove = new Image();

//Provide the source directory of the image you are about to upload.
dove.src = "Images/Image Manipulation/Doves.png";

// Make sure the image is loaded before you draw it on the canvas
dove.onload = function() {

// Draw the original image at location (0,0). This is only for reference.
ctx.drawImage(dove, 0, 0);

//Clip a 100 X 100 area starting at (40,95), scale it to 200 X 200 and draw at location //(450,0)
ctx.drawImage(dove,40,95,100,100,450,0,200,200);
}
}
}
  </script>
  <title>Clip an image</title>
</head>
<body onload="init();">
<canvas id="canvas" width="900" height="500"></canvas><br>
</body>
</html>
 
Try Code