美文网首页
js图片压缩

js图片压缩

作者: 肆意放纵 | 来源:发表于2019-07-18 16:17 被阅读0次

    懒需要解释吗?

     function 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
            }
     //调用
     this.compressedPicture(这里放base64的图, _ => {
                    console.log(_);
     })
    
    

    相关文章

      网友评论

          本文标题:js图片压缩

          本文链接:https://www.haomeiwen.com/subject/diwllctx.html