There is a div that is 400px wide, and it has an img tag. When I load a square image, it stretches it, but I need it not to be stretched.

How can I fix it?

  • 2
    Try to write more detailed questions. To get an answer, explain what exactly you see the problem, what you want to get as a result, etc. - Kromster
  • there is a div which has a width of 400px and it has an img tag, when I load a square image it stretches it and I need it to be NOT a rotate - no nn

1 answer 1

How to convert a rectangular image into a square one, having compressed it a little, using Javascript ? I will give a simple example:

 $(document).ready(function() { $("input").on("change", e => { // Вешаем обработчик на input var reader = new FileReader(); reader.onload = function(event) { var img = new Image(); img.onload = function() { var side = Math.min(img.height, img.width); // Выбираем меньшую сторону изображения $("canvas").width(side).height(side); // Устанавливаем размер canvas равным стороне изображения $("canvas")[0].getContext("2d").drawImage(img, 0, 0); // Отрисовываем ужатую картинку // $("canvas")[0].getContext("2d").drawImage(img, 0, 0, side, side, 0, 0, side, side); // Отрисовываем обрезанную картинку } img.src = event.target.result; } reader.readAsDataURL(e.target.files[0]); // Читаем выбранные данные }); }); 
 canvas, input { display: block; margin-bottom: 20px; } 
 <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> <canvas></canvas> <input type="file" > 


UPD:

After updating your question, the meaning has changed, to put it mildly, drastically.
In order for the images not to stretch, you just need to specify the size of the img tag, use js here is meaningless! An example using this picture (400x400):

moon

 div { width: 800px; background-color: red; } img { width: 400px; height: 400px; } 
 <div> <img src="https://i.stack.imgur.com/I6coC.jpg"> </div> 

As you can see from the snippet, nothing stretches anywhere, let the width of the div and exceed the same dimension img