canvas 等比例压缩图片

// 图片压缩,默认同比例压缩
compressImg (URL, callback) {
  // 生成canvas
  let canvas = document.createElement('canvas')
  let ctx = canvas.getContext('2d')
  let image = new Image()
  image.setAttribute('crossOrigin', 'anonymous')
  image.src = URL
  let quality = 0.3
  image.onload = () => {
    canvas.width = image.width
    canvas.height = image.height
    ctx.drawImage(image, 0, 0, canvas.width, canvas.height)
    let newImageData = canvas.toDataURL('image/jpeg', quality)
    callback(newImageData)
  }
}

 

posted on 2019-06-13 14:02  明启心动  阅读(1713)  评论(0编辑  收藏  举报

导航