一、效果展示
缓若江海凝清光
.
二、代码
const uploadProgress = ref(); //上传进度//进度丝滑更新
//进度,时常
const ProgressChange = (targetPercent: number, duration: number) => {//performance.now() 是浏览器提供的一个高性能时间 API,它返回一个 DOMHighResTimeStamp,//这个时间戳提供了当前页面从加载到现在所经过的毫秒数,具有很高的精度,适合用来测量脚本执行时间、动画帧间隔等const startTime = performance.now();//获取当前进度const startPercent = uploadProgress.value;const step = (currentTime: number) => {// 计算当前进度const elapsedTime = currentTime - startTime;// 修改进度条的百分比实现动画效果let currentPercent = easeInOut(elapsedTime,startPercent,targetPercent - startPercent,duration);// 确保百分比不超过100且不小于0currentPercent = Math.min(Math.max(currentPercent, 0), 100);// 更新进度条uploadProgress.value = Math.round(currentPercent);// 如果动画未结束,继续执行动画if (currentPercent < 100 && elapsedTime < duration) {requestAnimationFrame(step);} else {uploadProgress.value = Math.round(targetPercent); // 确保最终值准确无误}};// 使用函数使动画更加平滑const easeInOut = (t: number, b: number, c: number, d: number) => {t /= d / 2;if (t < 1) return (c / 2) * t * t * t + b;t -= 2;return (c / 2) * (t * t * t + 2) + b;};requestAnimationFrame(step);
};//选择文件
const handleFileChange = async (event: any) => {uploadProgress.value = 0;const file = event.target.files[0];fileNmae.value = file.name;if (file) {const reader = new FileReader();const updateProgress = (event: ProgressEvent) => {if (event.lengthComputable) {const totalDuration = 1000; // 1秒,单位为毫秒const percentComplete = (event.loaded / event.total) * 100;ProgressChange(percentComplete, totalDuration);}};reader.readAsDataURL(file);reader.onprogress = updateProgress;reader.onload = (e) => {if (typeof e.target?.result == "string") {imageUrl.value = e.target.result;}reader.onprogress = null;fileInfo.size = Number((file.size / 1024).toFixed(2));};}
三、实现原理
1.通过performance.now()获取动画的时间戳,用于创建流畅的动画。
2.通过一个缓动函数来实现动画的过渡效果。
3.通过requestAnimationFrame这个API来更新动画帧,优化显示效果。