CSS: make the canvas as large as possible while maintaining the aspect ratio

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 as large as possible, but at the same time keep the aspect ratio of the image. I know neither the aspect ratio of the image, nor the size of the div container, since this refers to the size of the user's screen / window.

If I set the maximum width and maximum height, for example 100%, the canvas does not fill the container if the selected image is smaller than the container. If I set the width and height instead of max-width and max-height, the canvas does not maintain the aspect ratio.

Does anyone have an idea how to solve this?

+4
source share
2 answers

If you want to use jQuery (or plain JavaScript), then a solution like this may occur:

<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 means is that it finds a ratio to multiply the width and height by, depending on which is smaller (so that it always enters the window).

Update: tested on JSFiddle.net. See here .

Hope this helps you!

+3
source

After reading your clarification about the video, check the following:

https://jsfiddle.net/d0dox9xt/

body {
    background: #eee;
}

#container {
    margin:0 2% 0 2%;
}

#v {
    position:absolute;
    top:0;
    left:0;
    width:100%;
}

The only trick is setting the width: 100%; This will maintain aspect ratio.

Please note that in JS

document.addEventListener('DOMContentLoaded', function(){
    var v = document.getElementById('v');
    var canvas = document.getElementById('c');
    var context = canvas.getContext('2d');
}

function draw(v) {
    c.drawImage(v, 0, 0);
}

drawImage . - , - . , . , CSS.

: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage

0

Source: https://habr.com/ru/post/1609111/


All Articles