前端js 通过canvas压缩图片

// 通过canvas压缩图片
canvasCompress(file) {
          var reader = new FileReader()
          var img = new Image()
          reader.readAsDataURL(file)
          reader.onload = function(e) {
            console.log('读取完成', e)
            img.src = this.result
          }
          var width = 480 // 图像大小
          var quality = 0.7 // 图像质量
          var canvas = document.createElement('canvas')
          var drawer = canvas.getContext('2d')
          var base64
          img.onload = function() {
            canvas.width = width
            canvas.height = width * (img.height / img.width)
            drawer.drawImage(img, 0, 0, canvas.width, canvas.height)
            base64 = canvas.toDataURL('image/jpeg', quality)
            console.log('压缩后', base64)
          }
        },

你可能感兴趣的:(前端js 通过canvas压缩图片)