Skip to content

Instantly share code, notes, and snippets.

@jonshipman
Created May 23, 2024 21:37
Show Gist options
  • Save jonshipman/060aa7a4d6e1560319f37152a08153b1 to your computer and use it in GitHub Desktop.
Save jonshipman/060aa7a4d6e1560319f37152a08153b1 to your computer and use it in GitHub Desktop.
Hero background component
<script lang="ts">
import { house } from '$lib/graphics';
import { page } from '$app/stores';
import type { WpPost } from '$lib/wp';
let bgMp4: string | undefined | null;
let bgWebm: string | undefined | null;
let post: WpPost | undefined;
$: post = $page.data.post;
$: bgMp4 = post?.hero_video_src;
$: bgWebm = post?.hero_video_webm_src;
function featuredImage(post: WpPost | undefined) {
let media: string = '';
try {
if (post) {
media =
post._embedded?.['wp:featuredmedia']?.[0]?.media_details.sizes?.['2048x2048']
?.source_url || '';
if (!media) {
media = post._embedded?.['wp:featuredmedia']?.[0].source_url || '';
}
}
} catch {
media = '';
}
return media || house;
}
function videoLoad(node: HTMLVideoElement, videos: [typeof bgMp4, typeof bgWebm]) {
function update(updatedVideos: [typeof bgMp4, typeof bgWebm]) {
if (updatedVideos[0] && node.canPlayType('video/mp4')) {
node.src = updatedVideos[0];
} else if (updatedVideos[1]) {
node.src = updatedVideos[1];
}
}
update(videos);
return { update };
}
</script>
{#if bgMp4}
<div class="bg-blue absolute inset-0 overflow-hidden">
<video
muted
loop
autoplay
class="w-full h-full object-cover mix-blend-multiply grayscale opacity-50"
use:videoLoad={[bgMp4, bgWebm]}
>
<source src={bgMp4} type="video/mp4" />
{#if bgWebm}
<source src={bgWebm} type="video/webm" />
{/if}
</video>
</div>
{:else}
<div
class="background absolute inset-0 mix-blend-multiply"
style="--bg: no-repeat center/cover url('{featuredImage(post)}');"
/>
{/if}
<style lang="postcss">
.background {
background:
linear-gradient(180deg, rgba(0, 41, 70, 0.78) 7.65%, rgba(0, 81, 138, 0.82) 100%),
var(--bg, transparent),
lightgray 50% / cover no-repeat;
}
</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment