<template>
	<div class="test" ref="testRef">
		<!-- <div class="canvas-container">
			<canvas id="canvas"></canvas>
		</div> -->
	</div>
</template>

<script lang="ts" setup>
	import { fabric } from "fabric-with-all";
	import { ref, watch, onMounted } from "vue";
	const imageUrl = "/src/assets/images/canvas/xiangaofenge.png";
	const testRef = ref(null);

	var canvas = null;
	onMounted(() => {
		canvas = new fabric.Canvas("canvas");
		canvas.setWidth(800);
		canvas.setHeight(600);
		// fabric.Image.fromURL(imageUrl, (img) => {
		// 	console.log(img.getElement());
		// 	img.set({
		// 		scaleX: 0.5,
		// 		scaleY: 0.5,
		// 	});
		// 	canvas.add(img);
		// });
		const image = new Image();
		image.src = imageUrl;
		image.onload = () => {
			const canvas1 = document.createElement("canvas");
			const width = image.width / 2;
			const height = image.height / 2;
			canvas1.width = width;
			canvas1.height = height;
			const ctx1 = canvas1.getContext("2d");
			ctx1.drawImage(image, 0, 0, width, height);
			const data = ctx1.getImageData(0, 0, width, height);
			testRef.value.appendChild(canvas1);
			const testData = test(data);
			const canvas2 = document.createElement("canvas");
			canvas2.width = width;
			canvas2.height = height;
			const ctx2 = canvas2.getContext("2d");
			ctx2.putImageData(testData, 0, 0);
			testRef.value.appendChild(canvas2);
		};
	});
	// 获取图片轮廓点位
	function test(data) {
		// 找过的点位
		const visited = [];
		// 轮廓点位
		const contours = [];
		const { width, height } = data;
		function cd(x, y) {
			const arr = [
				[x, y], // 当前
				[x, y - 1], // 上
				[x + 1, y], // 右
				[x, y + 1], // 下
				[x - 1, y], // 左
			];
			for (let i = 0; i < arr.length; i++) {
				let [x1, y1] = arr[i];
				if (x1 < 0 || x1 >= width || y1 < 0 || y1 >= height) continue;
				let key = `${x1},${y1}`;
				if (visited.includes(key)) continue;
				visited.push(key);
				let index = (y1 * width + x1) * 4;
				let r = data.data[index];
				let g = data.data[index + 1];
				let b = data.data[index + 2];
				let a = data.data[index + 3];
				if ((r || g || b) && a) {
					contours.push({ x: x1, y: y1 });
				} else {
					if (i > 0) cd(x1, y1);
				}
			}
		}
		cd(0, 0);
		console.log(contours);
		return data;
	}
</script>

<style lang='less' scoped>
	.test {
		.canvas-container {
			display: inline-block;
			border: 1px solid #000;
		}
	}
</style>