Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
79
rated 0 times [  84] [ 5]  / answers: 1 / hits: 26671  / 10 Years ago, fri, march 21, 2014, 12:00:00

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.


More From » html

 Answers
44

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


[#71869] Wednesday, March 19, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lewis

Total Points: 739
Total Questions: 100
Total Answers: 94

Location: Nepal
Member since Mon, Jan 4, 2021
3 Years ago
;