canvas进行图片尺寸压缩

707 阅读1分钟

压缩为尺寸压缩 

上代码

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图片尺寸压缩</title>
</head>

<body>
    <input id="fileInput" type="file">
    <input id="textInput" type="text" placeholder="请输入压缩比例">
    <button id="btn">压缩</button>
    <br><br>
    <!-- 预览图片 -->
    <img id="img1" src="" alt="">
    <!-- 压缩图片 -->
    <img id="img2" src="" alt="">
    <script>
        //获取dom
        const fileInput = document.getElementById('fileInput');
        const textInput = document.getElementById('textInput');
        const img1 = document.getElementById('img1');
        const img2 = document.getElementById('img2');
        const btn = document.getElementById('btn');

        //用于图片预览
        const rea = new FileReader();

        //创建canvas
        const c = document.createElement('canvas');
        c.style.display = 'none';
        document.body.appendChild(c);
        const ctx = c.getContext("2d");

        //图片预览
        rea.onload = function (e) {
            img1.src = e.target.result;
        }
        fileInput.onchange = function (e) {
            rea.readAsDataURL(e.target.files[0]);
        }

        //压缩函数
        function doSubmit() {
            if (fileInput.files.length <= 0) {
                alert('请先选择图片');
                return;
            }
            let ratio = Number(textInput.value);
            if (ratio <= 0 || ratio > 4) {
                alert('请输入大于0小于4的数字');
                return;
            }

            let width = img1.width * ratio;
            let height = img1.height * ratio;
            c.width = width
            c.height = height;
            ctx.drawImage(img1, 0, 0, width, height);
            let src = c.toDataURL('image/png');
            img2.src = src;
            console.log('压缩后的图片src', src);

        }
        btn.onclick = doSubmit;
        textInput.onkeypress = function (e) {
            let code = e.keyCode || e.which || e.charCode;
            if (code == 13) {
                doSubmit();
            }
        }
    </script>
</body>

</html>

注意点

1.需要绘制的img的src如果是路径导入或者是网址,图片路径与当前页面路径不同源,canvas会因为画布污染报错(浏览器的同源策略),使用base64不会受此限制
报错内容:Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.