roadrunner009
roadrunner009

Reputation: 29

How to resize images to fit my canvas?

I have images of different sizes and I am trying to use them as a background on a canvas.

index.html:

<!DOCTYPE html>
<html>
<head>
  <title>js</title>
</head>
<body onLoad='init2()'>
  <canvas id="canvas" width="1000" height="1000">
    This text is displayed if your browser does not support HTML5 Canvas.
   </canvas>

<!-- This image will be displayed on the canvas -->   
<img id="myImage" src="https://image.slidesharecdn.com/bareconf-140329111624-phpapp02/95/draft-scientific-paper-1-638.jpg?cb=1396091812" style = "display: none">
</body>
</html>  

How can I resize all the images to my canvas size which is fixed? Here is the full code.

When I change to this image, it is not resizing to my canvas dimensions.

Which is better, to resize all my images or my canvas?

Upvotes: 0

Views: 2441

Answers (1)

abdul-wahab
abdul-wahab

Reputation: 2272

You can use 4rth and 5th parameter of drawImage to define target width and height of the source image.

You can use:

void ctx.drawImage(image, dx, dy, dWidth, dHeight);

If you provide dx, dy as 0, 0 (as you are already providing in your example code) and dWidth and dHeight to canvas width and height, the source image will stretch to whole canvas.

If your source image has different aspect ratio and stretching it behind whole canvas disturbs it, you can use the following version:

void ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);

sx, sy are source image's start x, start y coordinate (which implicitly in previous version was 0, 0) and sWidth, sHeight are source image's width and height you want to pick and place on canvas.

So using start x, start y and width and height of source image, you can smartly choose a partition of source image so that when it stretches on whole canvas, aspect ratio should not get distorted.

MDN Reference.

Upvotes: 2

Related Questions