<template>
<div>
<A a="456" title="123"></A>
<img
width="300"
height="300"
id="img"
src="../assets/images/WX20240626-093815.png"
alt=""
/>
</div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import A from "./A.vue";
import useBase64 from "./index";
useBase64({
el: "#img",
}).then((res) => {
console.log(res);
});
</script>
<style scoped lang="scss"></style>
封装组件
import { onMounted } from 'vue'
type Options = {
el: string
}
export default function (option: Options): Promise<{ baseUrl: string }> {
return new Promise((resolve, reject) => {
onMounted(() => {
const img: HTMLImageElement = document.querySelector(
option.el
) as HTMLImageElement
if (img) {
img.onload = () => {
resolve({
baseUrl: base64(img),
})
}
} else {
reject('没有找到元素')
}
})
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')
}
})
}