vue3+canvas 绘制坐标
在Vue 3中,你可以创建一个自定义组件来使用Canvas绘制坐标系。以下是一个简单的例子:
<template>
<canvas ref="canvas" @click="drawCoordinate($event)"></canvas>
</template>
<script setup>
import { ref, onMounted } from 'vue';
const canvas = ref(null);
const drawCoordinate = (event) => {
const ctx = canvas.value.getContext('2d');
const rect = canvas.value.getBoundingClientRect();
ctx.clearRect(0, 0, canvas.value.width, canvas.value.height); // Clear canvas
ctx.beginPath();
ctx.strokeStyle = '#000';
ctx.lineWidth = 2;
ctx.setLineDash([5, 15]);
// Draw x axis
ctx.moveTo(rect.left, event.clientY - rect.top);
ctx.lineTo(rect.left + canvas.value.width, event.clientY - rect.top);
// Draw y axis
ctx.moveTo(event.clientX - rect.left, rect.top);
ctx.lineTo(event.clientX - rect.left, rect.top + canvas.value.height);
ctx.stroke();
};
onMounted(() => {
canvas.value.width = canvas.value.offsetWidth;
canvas.value.height = canvas.value.offsetHeight;
});
</script>
<style>
canvas {
border: 1px solid #000;
cursor: crosshair;
}
</style>
这个组件在被挂载后会设置canvas的宽度和高度,然后在canvas上绘制坐标系。用户点击canvas时,会绘制出点击位置的X轴和Y轴。使用setLineDash
方法设置虚线样式。
评论已关闭