8

I want to have an image inside a canvas element. The canvas will have static size (e.g 800x600) but the Image can be larger or smaller. So if the Image is smaller there will be white area round the image, if it is larger the image will not fit the canvas so some parts of the image won't be visible. What i want to ask is the following. Can I resize the image to fit canvas (e.g after user input) after the image has rendered on canvas?

html

<canvas id="myCanvas" width="800" height="600">

js

canvas = document.getElementById('myCanvas');
context = canvas.getContext('2d');
image = new Image();
image.src = 'url_to_image';
//lets say image is 400x300;
//will this work too?
image.width = image.width*2;
image.height = image.height * 2;
context.drawImage(image, 0, 0);
//or should i use this?
//context.drawImage(image, 0, 0, image.width*2, image.height * 2);

The second one stretches the image to fit the canvas. Can I stretch the image before calling drawImage (by editing image.width and image.height)? I have seen some editing software that zooms on the image and canvas stays static, without changing its size.

Neuron
  • 5,141
  • 5
  • 38
  • 59
Apostolos
  • 7,763
  • 17
  • 80
  • 150

1 Answers1

20

Not correct:

image.width = image.width*2;
image.height = image.height * 2;
context.drawImage(image, 0, 0);

as image's width and height properties are read-only.

Correct:

context.drawImage(image, 0, 0, image.width*2, image.height * 2);

Here is another way to make the image fit the canvas independent on aspect ratio:
Simulation background-size: cover in canvas

Community
  • 1
  • 1