439 字
2 分钟
Fuwari实现视频横幅
🤖AI 摘要

该博客介绍在 Fuwari 中实现视频横幅的方法,通过判断 src 文件扩展名是否为视频格式,来动态决定渲染<img>、Astro <Image><video>标签。

** 实现逻辑步骤如下:**#

1.识别视频格式#

const videoExtensions = [".mp4", ".webm", ".ogg"];
const cleanSrc = src.split("?")[0]; // 去掉 URL 参数
const ext = path.extname(cleanSrc).toLowerCase();
const isVideo = videoExtensions.includes(ext);

2.渲染判断分支#

{!isVideo && isLocal && img && (
<Image src={img} ... />
)}
{!isVideo && !isLocal && (
<img src={...} ... />
)}
{isVideo && (
<video src={...} ... />
)}
步骤功能
1️⃣ 判断扩展名区分图片与视频:isVideo = ext in [“.mp4”, “.webm”, “.ogg”]
2️⃣ 条件渲染isVideo 决定用

只需要传入带有视频扩展名的 src,组件就会自动切换到

完整代码#

src/components/misc/ImageWrapper.astro
---
import path from "node:path";
import { Image } from "astro:assets";
import { url } from "../../utils/url-utils";
interface Props {
id?: string;
src: string;
class?: string;
alt?: string;
position?: string;
basePath?: string;
poster?: string;
}
// 解构 Astro.props
const {
id,
src,
alt,
position = "center",
basePath = "/",
class: className,
poster,
} = Astro.props;
const imageClass = "w-full h-full object-cover";
const imageStyle = `object-position: ${position}`;
// 判断资源类型
const videoExtensions = [".mp4", ".webm", ".ogg"];
const cleanSrc = src.split("?")[0];
const ext = path.extname(cleanSrc).toLowerCase();
const isVideo = videoExtensions.includes(ext);
// 图片路径判断
const isLocal = !(
src.startsWith("/") ||
src.startsWith("http") ||
src.startsWith("https") ||
src.startsWith("data:")
);
const isPublic = src.startsWith("/");
// 加载本地图像资源
let img;
if (isLocal && !isVideo) {
const files = import.meta.glob<ImageMetadata>("../../**", {
import: "default",
});
let normalizedPath = path
.normalize(path.join("../../", basePath, src))
.replace(/\\/g, "/");
const file = files[normalizedPath];
if (!file) {
console.error(
`\n[ERROR] Image file not found: ${normalizedPath.replace("../../", "src/")}`,
);
console.log("Available files:", Object.keys(files));
} else {
img = await file();
}
}
---
<div id={id} class:list={[className, 'overflow-hidden relative']}>
<div class="transition absolute inset-0 dark:bg-black/10 bg-opacity-50 pointer-events-none"></div>
{!isVideo && isLocal && img && (
<Image src={img} alt={alt || ""} class={imageClass} style={imageStyle} />
)}
{!isVideo && !isLocal && (
<img src={isPublic ? url(src) : src} alt={alt || ""} class={imageClass} style={imageStyle} />
)}
{isVideo && (
<video
src={isPublic ? url(src) : src}
class={imageClass}
style={imageStyle}
autoplay
muted
loop
playsinline
poster={poster}
/>
)}
</div>
Fuwari实现视频横幅
https://fuwari.vercel.app/posts/bjk/fuwari实现视频横幅/
作者
Ke.ke
发布于
2024-06-27
许可协议
CC BY-NC-SA 4.0