rsnext/packages/next/shared/lib/image-blur-svg.ts
Steven fe762d329f
Fix next/image svg blur placeholder with fill (#41573)
This PR fixes two bugs:

- Fixes #40419 
- Fixes #41393 

The first is when the aspect ratio of the `width` and `height` does not
match the aspect ratio of the `blurDataURL` provided. This can result in
artifacts around the edges. The solution is to add
`preserveAspectRatio="none"`.

The second is when there is no `width` or `height` provided (which is
normal when using `fill`) so the viewBox was undefined. This can also
cause artifacts around the edges. The solution is to change the blur
technique from gaussian to css filter, similar to `next/legacy/image`.

Note: css blur might be [slower in
firefox](https://bugzilla.mozilla.org/show_bug.cgi?id=925025) which is
why we'll only use it for this corner case.
2022-10-19 13:21:41 -07:00

27 lines
1.2 KiB
TypeScript

/**
* A shared function, used on both client and server, to generate a SVG blur placeholder.
*/
export function getImageBlurSvg({
widthInt,
heightInt,
blurWidth,
blurHeight,
blurDataURL,
}: {
widthInt?: number
heightInt?: number
blurWidth?: number
blurHeight?: number
blurDataURL: string
}): string {
const std = blurWidth && blurHeight ? '1' : '20'
const svgWidth = blurWidth || widthInt
const svgHeight = blurHeight || heightInt
const feComponentTransfer = blurDataURL.startsWith('data:image/jpeg')
? `%3CfeComponentTransfer%3E%3CfeFuncA type='discrete' tableValues='1 1'/%3E%3C/feComponentTransfer%3E%`
: ''
if (svgWidth && svgHeight) {
return `%3Csvg xmlns='http%3A//www.w3.org/2000/svg' viewBox='0 0 ${svgWidth} ${svgHeight}'%3E%3Cfilter id='b' color-interpolation-filters='sRGB'%3E%3CfeGaussianBlur stdDeviation='${std}'/%3E${feComponentTransfer}%3C/filter%3E%3Cimage preserveAspectRatio='none' filter='url(%23b)' x='0' y='0' height='100%25' width='100%25' href='${blurDataURL}'/%3E%3C/svg%3E`
}
return `%3Csvg xmlns='http%3A//www.w3.org/2000/svg'%3E%3Cimage style='filter:blur(20px)' x='0' y='0' height='100%25' width='100%25' href='${blurDataURL}'/%3E%3C/svg%3E`
}