0
点赞
收藏
分享

微信扫一扫

vue 中压缩图片方法的封装

爱上流星雨 2022-02-11 阅读 71
vue.js前端

在src下新建的utils中,新建一个index.js文件,将封装方法写入:

/**
 * 压缩图片
 * @ file 图片文件
 * @ fileSize 图片文件的大小
 * @ callBack 压缩完成后的回调函数,参数:(base64)
 */
function compress(file, callBack) {
  var img = new window.Image();
  // 最大宽度
  var maxW = 640;
  // 压缩比
  var compressRate = 0.6;

  img.onload = function () {
    var cvs = document.createElement('canvas');
    var ctx = cvs.getContext('2d');

    if (img.width > maxW) {
      img.height *= maxW / img.width;
      img.width = maxW;
    }
    cvs.width = img.width;
    cvs.height = img.height;
    ctx.clearRect(0, 0, cvs.width, cvs.height);
    ctx.drawImage(img, 0, 0, img.width, img.height);

    var dataUrl = cvs.toDataURL('image/jpeg', compressRate);
    if (typeof callBack === 'function') {
      callBack(dataUrl);
    }
  };
  img.src = file
}

封装好的方法,在项目中引入,方法中调用即可

import { compress } from '@/utils'
举报

相关推荐

0 条评论