|
| 1 | +import { useEffect, useRef, useState } from 'react' |
| 2 | +import { decode } from 'blurhash' |
| 3 | + |
| 4 | +interface BlurhashImageProps { |
| 5 | + src: string |
| 6 | + blurhash?: string |
| 7 | + alt?: string |
| 8 | + style?: React.CSSProperties |
| 9 | +} |
| 10 | + |
| 11 | +const BLURHASH_WIDTH = 32 |
| 12 | +const BLURHASH_HEIGHT = 32 |
| 13 | + |
| 14 | +/** |
| 15 | + * blurhashプレースホルダー付き画像コンポーネント。 |
| 16 | + * blurhashが指定されていればロード中にぼかし画像を表示し、 |
| 17 | + * 画像ロード完了後にフェードインする。 |
| 18 | + */ |
| 19 | +export const BlurhashImage = (props: BlurhashImageProps) => { |
| 20 | + const [loaded, setLoaded] = useState(false) |
| 21 | + const canvasRef = useRef<HTMLCanvasElement>(null) |
| 22 | + |
| 23 | + useEffect(() => { |
| 24 | + if (!props.blurhash || !canvasRef.current) return |
| 25 | + try { |
| 26 | + const pixels = decode(props.blurhash, BLURHASH_WIDTH, BLURHASH_HEIGHT) |
| 27 | + const ctx = canvasRef.current.getContext('2d') |
| 28 | + if (!ctx) return |
| 29 | + const imageData = ctx.createImageData(BLURHASH_WIDTH, BLURHASH_HEIGHT) |
| 30 | + imageData.data.set(pixels) |
| 31 | + ctx.putImageData(imageData, 0, 0) |
| 32 | + } catch (e) { |
| 33 | + console.warn('Failed to decode blurhash:', e) |
| 34 | + } |
| 35 | + }, [props.blurhash]) |
| 36 | + |
| 37 | + // blurhashがない場合は通常のimgを返す |
| 38 | + if (!props.blurhash) { |
| 39 | + return <img src={props.src} alt={props.alt ?? ''} style={props.style} /> |
| 40 | + } |
| 41 | + |
| 42 | + return ( |
| 43 | + <div style={{ position: 'relative', overflow: 'hidden', lineHeight: 0 }}> |
| 44 | + <canvas |
| 45 | + ref={canvasRef} |
| 46 | + width={BLURHASH_WIDTH} |
| 47 | + height={BLURHASH_HEIGHT} |
| 48 | + style={{ |
| 49 | + position: 'absolute', |
| 50 | + top: 0, |
| 51 | + left: 0, |
| 52 | + width: '100%', |
| 53 | + height: '100%', |
| 54 | + objectFit: 'cover', |
| 55 | + opacity: loaded ? 0 : 1, |
| 56 | + transition: 'opacity 0.3s ease' |
| 57 | + }} |
| 58 | + /> |
| 59 | + <img |
| 60 | + src={props.src} |
| 61 | + alt={props.alt ?? ''} |
| 62 | + onLoad={() => setLoaded(true)} |
| 63 | + style={{ |
| 64 | + ...props.style, |
| 65 | + opacity: loaded ? 1 : 0, |
| 66 | + transition: 'opacity 0.3s ease' |
| 67 | + }} |
| 68 | + /> |
| 69 | + </div> |
| 70 | + ) |
| 71 | +} |
0 commit comments