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
The function accepts an options object with the following properties:
image: If provided, the function extracts the hash fromdata-blurhashordata-thumbhashattributes and calculates the aspect ratio from the element's dimensionshash: The hash string to decode. If bothimageandhashare provided,hashtakes precedencehashType: Specifies whether the hash is ablurhashorthumbhash. Default isblurhash. Ifimageis provided, the type is determined from the presence ofdata-blurhashordata-thumbhashattributessize: The size of the longer edge for BlurHash decoding. Default is32. This parameter is ignored for ThumbHashratio: The aspect ratio (width divided by height) for BlurHash. Ifimageis provided, this is calculated automatically using:(width || offsetWidth || size) / (height || offsetHeight || size). For optimal performance, set explicitwidthandheightHTML attributes to avoid falling back to rendered dimensions
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
<!-- Ensure the image has width and height attributes for optimal performance -->
<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