reactjs - 如何在我的 Gatsby 博客网站中有效地显示 GIF 图像?
问题描述
前几天买了一个盖茨比的博客主题,尝试修改。该博客站点使用图像(PNG、JPEG),而不是动画 GIF。所以我尝试在所有博客文章中使用 GIF 图片,但它影响了网站性能。另外,我注意到Gatsby Image不提供 GIF 格式。如何在我的博客上使用高性能的 GIF?
解决方案
您可以使用 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 图像转换器。它非常慢,将演示文稿与查询结合起来,并且不提供任何处理艺术指导的方法。
推荐阅读
- excel - 如何在包含工作簿页面的电子邮件正文中包含一条短信?
- javascript - 如何扩展打字稿接口?
- youtube-api - Zscaler 防火墙允许访问特定的嵌入式 Youtube 视频
- reactjs - 不断收到错误 MissingTranslationId
- spring-boot - 我可以在 Kubernetes 作业的 preStop 生命周期挂钩中使用 HTTP POST 吗?
- amazon-web-services - 将 CSV 数据加载到 Aurora Serverles MySQL 5.6 数据库集群中
- java - 如何将数组大小从 SHA-1 的输出 20 字节更改为适合 AES encryptopn 中的 IV 16 字节
- autocomplete - 在 zsh 中禁用完成缓存
- ios - UIImageView 约束为 1:1 纵横比和 1:1 缩放到原始?
- javascript - 位置固定时防止元素随页面滚动?