feat: 增加HoverImagePreview组件

This commit is contained in:
renxiaodong
2025-08-11 22:40:54 +08:00
parent 6eb302b0ae
commit 8cda6cae64
3 changed files with 142 additions and 5 deletions

View File

@ -298,3 +298,44 @@ export const generateFullUrl = (pathTemplate: string, params: Record<string, str
return `${baseUrl}${path}`;
};
/** 图片朝向类型 */
export type ImageOrientation = 'landscape' | 'portrait' | 'square';
/**
* 根据宽高判断图片是横图/竖图/正方形
*/
export const getImageOrientationBySize = (width: number, height: number): ImageOrientation => {
if (!width || !height) return 'square';
if (width > height) return 'landscape';
if (height > width) return 'portrait';
return 'square';
};
/**
* 加载图片自然尺寸(跨域下需服务端允许匿名访问)
*/
export const getImageNaturalSize = (url: string): Promise<{ width: number; height: number }> => {
return new Promise((resolve) => {
const img = new Image();
img.onload = () => {
resolve({ width: img.naturalWidth, height: img.naturalHeight });
};
img.onerror = () => {
resolve({ width: 0, height: 0 });
};
// 若是跨域资源并允许匿名访问,可尝试设置
try {
img.crossOrigin = 'anonymous';
} catch (_) {}
img.src = url;
});
};
/**
* 基于图片 URL 判断图片横竖
*/
export const getImageOrientationByUrl = async (url: string): Promise<ImageOrientation> => {
const { width, height } = await getImageNaturalSize(url);
return getImageOrientationBySize(width, height);
};