1 安装canvaskit-wasm
npm install canvaskit-wasm
或者
yarn add canvaskit-wasm
2 将文件node_modules/canvaskit-wasm/bin/canvaskit.wasm复制到public目录
3 引入到组件中
<template><img :src="imgData"/>
</template><script setup>import { ref } from 'vue'import CanvasKitInit from 'canvaskit-wasm'const imgData = ref('')CanvasKitInit({locateFile: (file) => {return `/${file}`},onRuntimeInitialized: () => {console.log('CanvasKit initialized!');}}).then(CanvasKit => {const skcanvas = CanvasKit.MakeCanvas(375, 600);const ctx = skcanvas.getContext('2d');const rgradient = ctx.createRadialGradient(50, 50, 10, 50, 50, 100);// Add three color stopsrgradient.addColorStop(0, 'red');rgradient.addColorStop(0.5, 'white');rgradient.addColorStop(1, 'blue');ctx.fillStyle = rgradient;ctx.globalAlpha = 0.7;ctx.fillRect(0, 0, 375, 600);imgData.value = skcanvas.toDataURL();})</script><style scoped></style>
4 预览效果
npm run dev