Resize a photo on canvas without losing proportions

Hello everyone for any help in advance. I am writing a phonegap application and cannot make the photo shrink without losing its aspect or cropping the image by mistake. In the function below "imageData" is a 64-bit line of the photo taken by the camera. I can draw an image on the canvas on my page, but if the photo was taken in a landscape, then it is broken together. If I do not scale it using the zoom function or the paint function, I get only the top corner of the photo. Example: I took a photo, the width of the image in the onPhotoDataSuccess function shows that it has a width of 1296 pixels and a height of 968 pixels. But my iPhone canvas is 272 pixels wide (portrait mode). I have tried many different scaling methods on the Internet, and this seems to be the closest not quite. What am I doing wrong?

function onPhotoDataSuccess(imageData) { var myImage = new Image(); var thecanvas = document.getElementById("queImg"); var ctx = thecanvas.getContext("2d"); myImage.onload = function() { thecanvas.setAttribute('width', '100%'); thecanvas.setAttribute('height', 'auto'); ctx.scale((myImage.width * 0.15), (myImage.height * 0.15)); ctx.drawImage(myImage, 0, 0); } myImage.src = "data:image/jpeg;base64," + imageData; } 
+4
source share
2 answers

Scaling is built into drawImage.

Do not use setAttribute when working with canvas, call canvas.width = 272 instead and only with integer pixel values.

Here is some working code for you:

  function onPhotoDataSuccess(imageData) { var myImage = new Image(); var thecanvas = document.getElementById("queImg"); var ctx = thecanvas.getContext("2d"); myImage.onload = function() { ctx.drawImage(myImage, 0, 0, myImage.width * 0.15, myImage.height * 0.15); } myImage.src = "http://placekitten.com/1296/968"; } onPhotoDataSuccess(null); 

Real-time example:

http://jsfiddle.net/QBTrg/6/

+5
source

You can simply draw like this without the scale function:

 ctx.drawImage(myImage, 0, 0, myImage.width * 0.15, myImage.height * 0.15); 

However, permission must be specified explicitly, not as a percentage. For instance:.

 window.onload = function() { thecanvas.width = window.width; thecanvas.height = window.height; } 
+1
source

All Articles