img编码为base64字符串

67 阅读1分钟

导读: base64不是加密算法,他只是一种编码方式,数据从一种形式转换为另一种形式进行传输/存储。

1、核心逻辑:编写hook

import { onMounted } from "vue"

type optionType = {
  el: string,
}
export default function useBase(option: optionType) {
  return new Promise<{ baseUrl: string }>(resolve => {
    onMounted(() => {
      const image = document.querySelector(option.el) as HTMLImageElement
      image.onload = () => {
        const canvas = document.createElement('canvas')
        const ctx = canvas.getContext('2d')
        canvas.width = image.width
        canvas.height = image.height

        ctx?.drawImage(image, 0, 0, image.width, image.height)
        resolve({ baseUrl: canvas.toDataURL('image/png') })
      }
    })
  })
}

2、应用一下

<img class="useBox" src="@/assets/images/yes/0x300a0a0 (2).png" alt="" /> 

useBase({ el: '.useBox' }).then(res => {
  // console.log(res.baseUrl)
})