Skip to content

Instantly share code, notes, and snippets.

@DonHuskini
Last active November 17, 2021 15:16
Show Gist options
  • Save DonHuskini/e9ffaeb813362e7eeaeb30d567667260 to your computer and use it in GitHub Desktop.
Save DonHuskini/e9ffaeb813362e7eeaeb30d567667260 to your computer and use it in GitHub Desktop.
Image Incremental Loading
import styled from '@emotion/styled'
import Image from 'next/image'
import { useProgressiveImage } from 'src/hooks/useProgressiveImage'
export function BlurredUpImage({ tiny, large, width, height, alt }) {
const [src, { blur }] = useProgressiveImage(tiny, large)
return <StyledImage src={src} width={width} height={height} alt={alt} blur={blur} />
}
const StyledImage = styled(Image)`
filter: ${({ blur }) => (blur ? 'blur(20px)' : 'none')};
transition: ${({ blur }) => (blur ? 'none' : 'filter 0.3s ease-out, transform 0.3s ease')};
clip-path: inset(0);
`
<Image
src={scene.img}
layout='fill'
objectFit='cover'
placeholder='blur'
blurDataURL={scene.base64}
alt='bg'
/>
<CreatureWrapper style={{ opacity: opacity.to({ range: [0.0, 1.0], output: [0, 1] }) }}>
<BlurredUpImage
large='/assets/creature-1.png'
tiny='/assets/creature-1-small.png'
width={500}
height={500}
objectFit='cover'
alt='character'
/>
</CreatureWrapper>
import { useEffect, useState } from 'react'
export const useProgressiveImage = (lowQualitySrc, highQualitySrc) => {
const [src, setSrc] = useState(lowQualitySrc)
useEffect(() => {
setSrc(lowQualitySrc)
const img = new Image()
img.src = highQualitySrc
img.onload = () => {
setSrc(highQualitySrc)
}
}, [lowQualitySrc, highQualitySrc])
return [src, { blur: src === lowQualitySrc }]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment