实用方法整理 Posted on 2017-03-23 | In 工作笔记 压缩照片(通过canvas实现) 123456789101112131415161718192021222324compressImage(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 12345678910111213141516171819202122232425262728293031scrollTop(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);}