Skip to content

🖼️ 图片加载蒙层动画组件

📝 需求背景

在网页开发中,图片加载往往会出现从上到下逐步显示的视觉割裂感,这种体验并不理想。为了优化用户体验,我们可以在图片加载完成前显示一个优雅的加载动画,等待图片完全加载后再展示。

✨ 特性

  • 支持多种加载动画样式(spinner/threeRotate)
  • 自定义样式配置
  • 响应式布局支持
  • 简单易用的 React 组件封装

🚀 使用示例

jsx
import { ImageOverlay } from './ImageOverlay';

// 基础使用
<ImageOverlay 
  src="your-image-url.jpg"
  alt="示例图片"
  type="spinner"
/>

// 自定义样式
<ImageOverlay 
  src="your-image-url.jpg"
  alt="示例图片"
  type="threeRotate"
  style={{
    width: '300px',
    height: '200px'
  }}
/>

💡 核心实现

jsx
import style from './imageOverlay.module.css'
import React, { useState } from 'react';

const ImageOverlay = ({ style: customStyle, src, alt, type }) => {
  const [loading, setLoading] = useState(true);
  
  const handleImageLoad = () => {
    setLoading(false);
  };

  const containerStyle = {
    position: 'relative',
    width: '100%',
    height: '100%',
    ...customStyle
  };

  const imgStyle = {
    display: loading ? 'none' : 'block',
    width: '100%',
    height: '100%',
  };

  return (
    <>
      {type === 'spinner' && (
        <div style={containerStyle}>
          {loading && (
            <div className={style.overlayBox}>
              <div className={style.spinner}></div>
            </div>
          )}
          <img
            src={src}
            alt={alt}
            style={imgStyle}
            onLoad={handleImageLoad}
          />
        </div>
      )}
      
      {type === 'threeRotate' && (
        <div style={containerStyle}>
          {loading && (
            <div className={style.overlayBox}>
              <div className={style.loader}>
                <svg viewBox="0 0 80 80">
                  <rect x="8" y="8" width="64" height="64"></rect>
                </svg>
              </div>
            </div>
          )}
          <img
            src={src}
            alt={alt}
            style={imgStyle}
            onLoad={handleImageLoad}
          />
        </div>
      )}
    </>
  );
};

📌 注意事项

  1. 确保提供正确的图片 URL 地址
  2. 建议设置合适的容器尺寸
  3. 可以通过 customStyle 属性自定义容器样式
  4. 需要配套使用 CSS 模块文件定义动画样式

🎨 样式参考

建议在 imageOverlay.module.css 中定义以下样式:

css
.overlayBox {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgba(255, 255, 255, 0.8);
}

/* spinner 动画样式 */
.spinner {
  /* 在此添加 spinner 的 CSS 动画 */
}

/* threeRotate 动画样式 */
.loader {
  /* 在此添加 threeRotate 的 CSS 动画 */
}

🔍 进阶优化建议

  1. 添加加载失败的错误处理
  2. 支持更多类型的加载动画
  3. 添加图片预加载功能
  4. 支持懒加载配置
  5. 考虑添加渐变显示效果

🎉 小结

通过使用这个图片加载蒙层组件,可以有效改善用户体验,使图片加载过程更加平滑自然。组件的设计充分考虑了可定制性和易用性,适合在各种 React 项目中使用。