vue3+ts hooks的使用

	<template>
  <div>
    <img src="./assets/images/1.png" alt="" width="300" height="300" id="img" />
    <A a="456" title="123"></A>
  </div>
</template>

<script setup lang="ts">
import A from "./components/A.vue";
import useBase64 from "./hooks";

useBase64({
  el: "#img",
}).then((res) => {
  console.log(res.baseUrl);
});
</script>

<style></style>

hooks/index.ts:

import {onMounted } from "vue";


type Options = {
    el:string
}


export default function (options: Options):Promise<{baseUrl:string}> {

    return new Promise((resolve) => {
         onMounted(() => {
        let img: HTMLImageElement = document.querySelector(options.el) as HTMLImageElement;
        console.log(img, "===========>");
        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");
    }
    })
    
}

效果图:

vue3+ts hooks的使用_第1张图片

你可能感兴趣的:(vue.js,javascript,前端)