首页 > 解决方案 > 如何在我的 Gatsby 博客网站中有效地显示 GIF 图像?

问题描述

前几天买了一个盖茨比的博客主题,尝试修改。该博客站点使用图像(PNG、JPEG),而不是动画 GIF。所以我尝试在所有博客文章中使用 GIF 图片,但它影响了网站性能。另外,我注意到Gatsby Image不提供 GIF 格式。如何在我的博客上使用高性能的 GIF?

标签: reactjsperformancegatsbygif

解决方案


您可以使用 ffmpeg 将 GIF 转换为具有 H.264 编码的 MP4 视频。然后使用<video src="..." />代替您的img标签。为了让这变得非常简单,我有一个 React 组件用于此,它包括在视频可见时自动播放:

import React, { useEffect } from "react"
import PropTypes from "prop-types"
import { useInView } from "react-intersection-observer"

const GifVideo = ({ threshold = 0.15, ...playerProps }) => {
  const [ref, inView] = useInView({ threshold })

  useEffect(() => {
    if (inView) {
      ref.current?.play()
    } else {
      ref.current?.pause()
    }
  }, [ref, inView])

  return <video ref={ref} autoPlay playsInline muted loop {...playerProps} />
}

export default GifVideo

GifVideo.propTypes = {
  src: PropTypes.string,
  threshold: PropTypes.number,
  className: PropTypes.string,
}

然后你使用它,就这么简单:

<GifVideo src="/your/video.mp4" width={400} className="some-class" />

对于它的价值,我不建议在 Gatsby (gatsby-transformer-sharp) 中使用锐利的 GraphQL 图像转换器。它非常慢,将演示文稿与查询结合起来,并且不提供任何处理艺术指导的方法。


推荐阅读