1, the background

Displaying images on web pages is a very common requirement. In most cases, the size of the display area is fixed, as is the size of the original image

If the width and height of the display area are not proportional to the width and height of the original image, it is likely that by default the image will be compressed or stretched to fit the area

Let’s do a comparison experiment with two images, assuming that the display area is 300px wide and high

The horizontal images are 722px and 88px wide and the vertical images are 80px and 525px wide and high

<! DOCTYPEhtml>
<html>
<head>
    <style>
        .image {
            width: 300px;
            height: 300px;
        }
    </style>
</head>
<body>
    <img class="image" src="test.png">
</body>
</html>
Copy the code

2. Set CSS

Obviously, this is not what we want because it will cause the image to distort and compress, and we need to find a way to scale the image equally

The easiest way to do this is to set up CSS so that images automatically fit the size of the display area. The code is very simple

<! DOCTYPEhtml>
<html>
<head>
    <style>
        .image-box {
            width: 300px;
            height: 300px;
        }
        .image {
            width: auto;
            height: auto;
            max-width: 100%;
            max-height: 100%;
        }
    </style>
</head>
<body>
    <div class="image-box">
        <img class="image" src="test.png">
    </div>
</body>
</html>
Copy the code

3. Use Canvas

After setting the CSS style, the image will scale to the smallest edge, which can be used in most scenarios

But sometimes we want to have our cake and eat it too, so we have to crop the largest area of the image that can be scaled equally

In effect, the image is captured using a rectangle proportional to the display area, and the resulting image is required to be as large as possible and located in the center of the original image

<! DOCTYPEhtml>
<html>
<head>
    <script>
        window.onload = function() {
            let cvs = document.querySelector('#image')
            let ctx = cvs.getContext('2d')
            let img = new Image()
            img.src = 'test.png'
            img.onload = () = > {
                let adaptedImage = adaptImage(0.0, img.width, img.height, 0.0, cvs.width, cvs.height) ctx.drawImage(img, ... adaptedImage) } }function adaptImage(imgX, imgY, imgW, imgH, cvsX, cvsY, cvsW, cvsH) {
            let idealW = imgW
            let idealH = cvsH + (imgW - cvsW) * (cvsH / cvsW)
            if (idealH <= imgH) {
                return [0, imgH / 2 - idealH / 2, idealW, idealH, cvsX, cvsY, cvsW, cvsH]
            } else {
                idealH = imgH
                idealW = cvsW + (imgH - cvsH) * (cvsW / cvsH)
                return [imgW / 2 - idealW / 2.0, idealW, idealH, cvsX, cvsY, cvsW, cvsH]
            }
        }
    </script>
</head>
<body>
    <canvas id="image" width="300" height="300">
</body>
</html>
Copy the code