From e31ec3d505f4067205998e3d472bbb9f72e34731 Mon Sep 17 00:00:00 2001 From: hzj <1304805162@qq.com> Date: Mon, 1 Dec 2025 19:13:29 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E6=96=B0=E5=B7=A5=E5=85=B7=E7=B1=BB):=20?= =?UTF-8?q?=E9=A2=84=E5=8A=A0=E8=BD=BD=E5=9B=BE=E7=89=87=E5=B7=A5=E5=85=B7?= =?UTF-8?q?=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/utils/imagePreloader.js | 55 +++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 src/utils/imagePreloader.js diff --git a/src/utils/imagePreloader.js b/src/utils/imagePreloader.js new file mode 100644 index 0000000..fb770e1 --- /dev/null +++ b/src/utils/imagePreloader.js @@ -0,0 +1,55 @@ +// src/utils/imagePreloader.js + +/** + * 简单图片预加载函数 + * @param {Array|string|Object} sources - 图片源(数组、字符串或对象) + */ +export const preloadImages = (sources) => { + let urls = [] + + if (Array.isArray(sources)) { + urls = sources + } else if (typeof sources === 'string') { + urls = [sources] + } else if (typeof sources === 'object') { + urls = Object.values(sources) + } + + urls.forEach((url) => { + const img = new Image() + img.src = url + }) + + console.log(`开始预加载 ${urls.length} 张图片`) +} + +/** + * 带进度监控的图片预加载函数 + * @param {Array|string|Object} sources - 图片源 + * @param {Function} onProgress - 进度回调 + */ +export const preloadImagesWithProgress = (sources, onProgress) => { + let urls = [] + + if (Array.isArray(sources)) { + urls = sources + } else if (typeof sources === 'string') { + urls = [sources] + } else if (typeof sources === 'object') { + urls = Object.values(sources) + } + + let loaded = 0 + const total = urls.length + + urls.forEach((url) => { + const img = new Image() + img.onload = img.onerror = () => { + loaded++ + if (onProgress) { + onProgress({ loaded, total, url }) + } + } + img.src = url + }) +}