createPlaceholderFromHash
Generates a PNG data URI placeholder from a BlurHash or ThumbHash string. This function is used internally by lazyLoad but can also be called directly for custom implementations.
Type Declarations
ts
export function createPlaceholderFromHash(options?: {
/** If present, the hash will be extracted from the image's `data-blurhash` or `data-thumbhash` attribute and ratio will be calculated from the image's actual dimensions. */
image?: HTMLImageElement
hash?: string
hashType?: 'blurhash' | 'thumbhash'
/** @default 32 */
size?: number
/** Will be calculated from the image's actual dimensions if image is provided and ratio is not. */
ratio?: number
}): string | undefinedParameters
| Parameter | Type | Default | Description |
|---|---|---|---|
image | HTMLImageElement | - | If provided, extracts hash from data-blurhash or data-thumbhash and calculates ratio from element dimensions |
hash | string | - | Hash string to decode. Takes precedence over image attributes |
hashType | 'blurhash' | 'thumbhash' | 'blurhash' | Hash format. Auto-detected when image is provided |
size | number | 32 | Size of the longer edge for BlurHash decoding. Ignored for ThumbHash |
ratio | number | - | Aspect ratio (width / height) for BlurHash. Auto-calculated from image if provided |
INFO
For BlurHash, set explicit width and height attributes on images. See placeholders guide for details.
Return Value
Returns a PNG data URI string if the hash is successfully decoded, or undefined if:
- No hash is provided
- The hash decoding fails
- The required decoding library is not available
Examples
Using with a hash string:
ts
import { createPlaceholderFromHash } from 'unlazy'
const placeholder = createPlaceholderFromHash({
hash: 'LKO2:N%2Tw=w]~RBVZRi};RPxuwH',
hashType: 'blurhash',
size: 32,
ratio: 16 / 9
})Using with an image element:
ts
import { createPlaceholderFromHash } from 'unlazy'
const img = document.querySelector('img')
const placeholder = createPlaceholderFromHash({
image: img
})
if (placeholder) {
img.src = placeholder
}html
<img
width="800"
height="600"
data-blurhash="LKO2:N%2Tw=w]~RBVZRi};RPxuwH"
>TIP
For server-side rendering, use the specialized functions instead:
createPngDataUrifromunlazy/blurhashcreatePngDataUrifromunlazy/thumbhash