1
0
mirror of https://github.com/elk-zone/elk synced 2024-12-22 10:37:59 +09:00
elk/components/common/CommonBlurhash.ts

47 lines
1.1 KiB
TypeScript
Raw Normal View History

2022-11-21 22:21:53 +09:00
import { decode } from 'blurhash'
2022-11-28 16:12:13 +09:00
import { getDataUrlFromArr } from '~/composables/utils'
2022-11-21 22:21:53 +09:00
export default defineComponent({
inheritAttrs: false,
props: {
blurhash: {
type: String,
required: true,
},
src: {
type: String,
required: true,
},
srcset: {
type: String,
required: false,
},
2022-11-21 22:21:53 +09:00
},
setup(props, { attrs }) {
const placeholderSrc = ref<string>()
const isLoaded = ref(false)
onMounted(() => {
const img = document.createElement('img')
img.onload = () => {
isLoaded.value = true
}
img.src = props.src
if (props.srcset)
img.srcset = props.srcset
2022-11-24 13:13:13 +09:00
setTimeout(() => {
isLoaded.value = true
}, 3_000)
2022-11-21 22:21:53 +09:00
if (props.blurhash) {
const pixels = decode(props.blurhash, 32, 32)
placeholderSrc.value = getDataUrlFromArr(pixels, 32, 32)
}
})
return () => isLoaded.value || !placeholderSrc.value
? h('img', { ...attrs, src: props.src, srcset: props.srcset })
2022-11-21 22:21:53 +09:00
: h('img', { ...attrs, src: placeholderSrc.value })
},
})