自定义hooks

自定义hook图片转base64

type Options = {
  el: string
}
export default function useBase64(options: Options): Promise<{ baseUrl: string }> {
  return new Promise(resolve => {
    onMounted(() => {
      const img: HTMLImageElement = document.querySelector(options.el) as HTMLImageElement
      img.onload = () => {
        resolve({ baseUrl: base64(img) })
      }
    })
    const base64 = (el: HTMLImageElement) => {
      const canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d')
      canvas.width = 500
      canvas.height = 300
      ctx?.drawImage(el, 0, 0, canvas.width, canvas.height)
      return canvas.toDataURL('image/png')
    }
  })
}

// 使用
import useBase64 from '../../hooks'
useBase64({ el: '#imgId' }).then(({ baseUrl }) => {
  console.log(baseUrl)
}) 
posted @ 2022-11-08 17:28  前端之旅  阅读(36)  评论(0)    收藏  举报