Falcon80 Logo
Scaling images on canvas

Canvas offers two directions along which you can scale an image viz., the x-coordinate and y-coordinate.

You can achieve scaling using the scale() method which takes two parameters:

1. The number of times by which the image should be scaled in the x-direction and

2. The number of times by which the image should be scaled in the y-direction.

Both parameters are float values.
Scaling image on canvas

Here, the original image is 100 X 100 pixels. The second image is scaled so that the dimensions become 150 X 100. To achieve this effect, we would have to multiply 100 pixels (width of the original image) by 1.5. There is no change to the height of the image. So we would multiply 100 pixels (height of the original image) by 1. Thus the scale() method would take in the parameters scale(1.5,1).

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 flower = new Image();

//Provide the source directory of the image you are about to upload
flower.src = "flower.png";

// Draw the original image at location (0,0) on the canvas
ctx.drawImage(flower, 0, 0);

// Now let's scale the image. We will increase the width by 1.5 times and height by 2 times and draw it alongside the original image for comparison
ctx.scale(1.5, 2.0);
ctx.drawImage(flower, 150, 0);
}
}
  </script>
  <title>Scaling an image on canvas</title>
</head>
<body onload="init();">
<canvas id="canvas" width="900" height="500"></canvas><br>
</body>
</html>
Note that the scale() method has to be called before you draw the image you are transforming and not after.

Try Code