Set HTML5 canvas height and width and content inside the scale

Is it possible to set the width and height of the canvas element and have an existing content scale in accordance with these new dimensions?

Now the user uploads the image, and my page creates a canvas element containing this image, and whose dimensions are the same size as the image. I want to limit the size I work with, however, here is an example of what I want:

  • The user uploads an image with a resolution of 1600 x 1200 pixels (not saved on the server)
  • Data goes straight to the html5 canvas object
  • The height and width of the canvas is set to 800 x 600, and the content of the image is scaled accordingly and then displayed.

Right now, if I set the width and height of the canvas, it just crop the image in this dimension, without resizing as we would like. Thanks!

+4
source share
2 answers

There are many ways to call drawImage

One of them:

ctx.drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh)

Where dx, dy, dw, dh is the destination x, y, width and height.

If you make dw and dh always 800x600, the drawn image will always automatically scale to 800x600.

Here is a tiny example that will always draw any image up to 800x600 in size http://jsfiddle.net/jAT8Y/

+4
source

Another alternative is to use the context.scale function. Image quality will be better if you use scale.

+1
source

All Articles