实用方法整理

压缩照片(通过canvas实现)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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);
}