js通过canvas封装压缩图片的方法

export const zipImg = (data, maxWidth = 800, maxHeight = 800) => {
  var img = new Image()
  const canvas = document.createElement('canvas');
  return new Promise((resolve, reject) => {

    //获取canvas2d的画布
    const context = canvas.getContext('2d')
    //图片加载完成时触发
    img.onload = function () {
      //图片尺寸
      const { width, height } = img
      //目标尺寸
      let targetWidth = width, targetHeight = height
      // 图片尺寸超过800x800的限制
      if (width > maxWidth || height > maxHeight) {
        if (width / height > maxWidth / maxHeight) {
          // 更宽,按照宽度限定尺寸
          targetWidth = maxWidth;
          targetHeight = Math.round(maxWidth * (height / width));
        } else {
          targetHeight = maxHeight;
          targetWidth = Math.round(maxHeight * (width / height));
        }
      }
      //canvas对图片进行缩放
      canvas.width = targetWidth
      canvas.height = targetHeight
      // 清除画布
      context.clearRect(0, 0, targetWidth, targetHeight);
      // 图片压缩
      context.drawImage(img, 0, 0, targetWidth, targetHeight);
      canvas.toBlob(function (blob) {
        resolve(blob)
      })
    }
    if (typeof data == "string") {
      img.src = data
    } else {
      let reader = new FileReader()
      reader.addEventListener('load', () => {
        img.src = <string>reader.result
        //console.log(reader.result)
      })
      reader.readAsDataURL(data)
    }
  })
}

你可能感兴趣的:(html5,javascript,vue.js)