Home.vue
<template>
<el-input v-model="Val" style="width: 400px"></el-input>
<el-button @click="imgHandler">过滤</el-button>
<hr />
<canvas id="myCanvas" width="500" height="500"></canvas>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import myImgs from "../../public/04.jpg";
const Val = ref("");
//定义画布
let canvas: any;
let ctx: any;
let img = new Image();
img.src = myImgs;
img.onload = function () {
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, 500, 500);
};
//创建webWorker,指向public/pic.ts
//地址需要是线上地址
let worker1 = new Worker("http://localhost:5173/pic.ts");
worker1.addEventListener("message", (e) => {
const imgData = e.data;
ctx.putImageData(imgData, 0, 0);
});
function imgHandler() {
//获取画布数据
const imageData = ctx.getImageData(0, 0, 500, 500);
//发送数据给worker
worker1.postMessage(imageData);
}
</script>
<style lang="scss" scoped></style>
pic.ts
self.addEventListener("message", (e) => {
if (e.data.data.length) {
let imgData = e.data;
for (let i = 0; i < imgData.data.length; i += 4) {
for (let j = 0; j < 25500; j++) {
if (imgData.data[i] !== 255) {
imgData.data[i] = Math.min(imgData.data[i] + j, 0);
}
}
}
self.postMessage(imgData);
}
});
效果