canvas 壓縮圖片的大小


使用 signature_pad canvas 庫生成的圖片太大。但又沒有提供方法來壓縮。

當然這是根據你canvas的畫布大小決定的,某些原因導致我的畫布就得是那么大。

隨隨便便一個圖片轉化為base64 之后就是200kb-300kb。所以得想辦法壓縮。

思路就是把生成的base64 圖片再一次放入canvas 中 ,然后等比縮小4倍即可。

save () {
    if (this.$refs.signature.isEmpty() === false) {
        // https://github.com/WangShayne/vue-signature
        var png = this.$refs.signature.save();
        this.compressedPicture(png, _ => {
            console.log(_);
        })
    }
},
compressedPicture (url, callback) {
    var canvas = document.createElement('canvas'); 
    var ctx = canvas.getContext('2d'); 
    var img = new Image; 
    img.onload = function(){
        console.log(img.width);
        var width = img.width;
        var height = img.height;
        // 按比例壓縮4倍
        var rate = (width < height ? width / height : height / width) / 4;
        canvas.width = width * rate; 
        canvas.height = height * rate; 
        ctx.drawImage(img, 0, 0, width, height, 0, 0, width * rate, height * rate); 
        var dataURL = canvas.toDataURL('image/jpeg'); 
        callback.call(this, dataURL); 
        canvas = null; 
        console.log(dataURL);
    };
    img.src = url
},

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM