Vue: 自定义hooks转img为base64
作者:互联网
import { onMounted } from 'vue' type Options = { elem: string } const base64 = (elem: HTMLImageElement) => { const canvas = document.createElement('canvas') const ctx = canvas.getContext(('2d')) canvas.width = elem.width canvas.height = elem.height ctx?.drawImage(elem, 0, 0, canvas.width, canvas.height) return canvas.toDataURL('image/png') } export default function (options: Options): Promise<{ baseUrl: string }> { return new Promise(resolve => { onMounted(() => { const imgElement: HTMLImageElement = document.querySelector(options.elem) as HTMLImageElement console.log(imgElement) imgElement.onload = () => { resolve({ baseUrl: base64(imgElement) }) } }) }) }
App.vue
<template> <div> <img src="@/assets/img.png" alt="" id="img"> <A a="555" title="666"></A> </div> </template> <script lang="ts" setup> import A from '@/components/A.vue' import useBase64 from '@/hooks/index.ts' useBase64({ elem: '#img' }).then(data => { console.log(data.baseUrl) }) </script>
A.vue
<template> <div class="a"> component A </div> </template> <script lang="ts" setup> import { useAttrs, useSlots } from 'vue' const attrs = useAttrs() console.dir(useAttrs) console.dir(attrs) const slots = useSlots() console.dir(useSlots) console.dir(slots) </script> <style scoped> .a { width: 200px; height: 200px; border: 2px inset palegreen; } </style>
标签:canvas,Vue,const,自定义,hooks,elem,height,vue,console 来源: https://www.cnblogs.com/dissipate/p/16058435.html