js 实现图片压缩

var images = new Image()
images.src = result  //  result  base64图片
images.onload = () => {
    let width = images.width // 图片宽度
    let height = images.height // 图片高度
    let dataUrl = compress(images, width, height, 0.1)

    console.log(dataUrl);  // 压缩后的base64图片

}


/* 
 * 图片压缩
 * img    原始图片
 * width   压缩后的宽度
 * height  压缩后的高度
 * ratio   压缩比率 
 */
function compress(img, width, height, ratio) {        
    var canvas, ctx, img64;
         
    canvas = document.createElement('canvas');        
    canvas.width = width;
    canvas.height = height;
         
    ctx = canvas.getContext("2d");        
    ctx.drawImage(img, 0, 0, width, height);
         
    img64 = canvas.toDataURL("image/jpeg", ratio);
         
    return img64;
}