Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: Make Canvas as big as possible while keeping aspect ratio

Tags:

html

css

canvas

I have a Canvas element that is inside a container div. When the user selects an image from his machine, this image should be displayed on the canvas. I want the canvas to be big as possible but at the same time keep the aspect ratio of the image. I know neither the proportions of the image nor the size of the container div, as this is relative to the screen/window size of the user.

If I set max-width and max-height to e.g 100% the canvas will not fill the container if the selected image is smaller then the container. If I set width and height instead of max-width and max-height the canvas doesn't keep the aspect ratio.

Does anyone have an idea how to solve this?

like image 475
DP. Avatar asked Sep 26 '15 18:09

DP.


People also ask

How do I resize an image using CSS without losing the aspect ratio?

The Simple Solution Using CSSBy setting the width property to 100%, you are telling the image to take up all the horizontal space that is available. With the height property set to auto, your image's height changes proportionally with the width to ensure the aspect ratio is maintained.

How do I keep aspect ratio in CSS?

In the CSS for the <div>, add a percentage value for padding-bottom and set the position to relative, this will maintain the aspect ratio of the container. The value of the padding determines the aspect ratio. ie 56.25% = 16:9.

How do you dynamically resize canvas?

Resizing the canvas on the fly is quite easy. To do it, simply set the width and height properties of the Canvas object, and then redraw the canvas contents: Canvas . width = 600 ; Canvas .

How do I make canvas size full screen?

Code to make canvas occupy full page :width = window. innerWidth; canvas. height = window. innerHeight; //Done!


1 Answers

If you're willing to use JQuery (or regular JavaScript), then a solution like this might work:

<script>

    // Note: this uses jQuery.
    // It makes getting/setting the dimensions easier,
    // but you can do this with normal JavaScript

    var img = $("#img");
    var container = $("#container");

    var width = img.width();
    var height = img.height();
    var maxWidth = container.width();
    var maxHeight = container.height();

    var ratio = maxWidth / width;
    if(height * ratio > maxHeight) {
        ratio = maxHeight / height;
    }
    img.width(width * ratio);
    img.height(height * ratio);

</script>

What this does is that it finds the ratio to multiply the width and the height by, whichever one is smaller (so that it will always fit in the window).

Update: Tested on JSFiddle.net. See it here.

I hope this helps you!

like image 188
Jonathan Lam Avatar answered Sep 27 '22 21:09

Jonathan Lam