实用方法整理

压缩照片(通过canvas实现)

compressImage(imageData, callback) {
  var img = new Image();
  var canvas = document.createElement('canvas');
  var ctx = canvas.getContext("2d");
  img.onload = function() {
    var width = 0;
    var height = 0;
    var scaleNumber;
    scaleNumber = Math.max(img.width, img.height) > MAX_IMAGE_LENGTH ? (MAX_IMAGE_LENGTH / Math.max(img.width, img.height)) : 1; // 如果照片大于要求大小,缩放到要求大小
    width = scaleNumber * img.width;
    height = scaleNumber * img.height
    canvas.width = width;
    canvas.height = height;
    ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, width, height);// 通过画布画上缩小后的图片再导出
    callback(canvas.toDataURL('image/jpeg', 0.8));
  }
  img.src = imageData;
}

// 使用示例
this.compressImage(reader.result, function(imageData) {
  let content = imageData.split('base64,')[1];
  me.addFile(content, file.name);
});

scrollTop

scrollTop(el, from = 0, to, duration = 500) {
  if (!window.requestAnimationFrame) {
    window.requestAnimationFrame = (
      window.webkitRequestAnimationFrame ||
      window.mozRequestAnimationFrame ||
      window.msRequestAnimationFrame ||
      function (callback) {
        return window.setTimeout(callback, 1000/60);
      }
    );
  }
  const difference = Math.abs(from - to);
  const step = Math.ceil(difference / duration * 50);// 根据duration拆分距离

  function scroll(start, end, step) {
    if (start === end) return;

    let d = (start + step > end) ? end : start + step;// 向后滚
    if (start > end) {
      d = (start - step < end) ? end : start - step;// 向前滚
    }

    if (el === window) {
      window.scrollTo(d, d);
    } else {
      el.scrollTop = d;
    }
    window.requestAnimationFrame(() => scroll(d, end, step));// 循环调用,一次滚一个step
  }
  scroll(from, to, step);
}
posted @ 2017-03-23 06:47  Erin.ma  阅读(119)  评论(0编辑  收藏  举报