CanvasBase64 发表于 2022-11-16 | 分类于 Hooks 图片通过canvas转base64 1234567891011121314151617181920212223242526272829303132import { onMounted } from 'vue'type Options = { el: string}export default function useBase64(options: Options): Promise<{ baseUrl: string }> { return new Promise((resolve) => { onMounted(() => { //获取图片实例 let 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 = el.width canvas.height = el.height ctx?.drawImage(el, 0, 0, canvas.width, canvas.height) return canvas.toDataURL('image/png') } }) // useBase64({ el: "#img" }).then(res => { // console.log(res.baseUrl); // })