生成一段vue代码,绘制一条折线,并可以沿着折线拖动一个圆形元素,拖动范围仅限折线上
时间: 2024-05-12 16:17:35 浏览: 213
vue 百度地图(vue-baidu-map)绘制方向箭头折线实例代码详解
可以尝试下面的Vue代码:
```
<template>
<div class="container">
<svg viewBox="0 0 500 300">
<path
class="line"
:d="line"
fill="none"
stroke="#333"
stroke-linecap="round"
stroke-linejoin="round"
/>
<circle
:cx="circleX"
:cy="circleY"
r="10"
fill="#007aff"
@mousedown="handleMouseDown"
@mousemove="handleMouseMove"
@mouseup="handleMouseUp"
/>
</svg>
</div>
</template>
<script>
export default {
data() {
return {
pathPoints: [
[0, 150],
[50, 100],
[100, 120],
[150, 60],
[200, 90],
[250, 130],
[300, 90],
[350, 80],
[400, 110],
[450, 70],
[500, 130]
],
circleX: 50,
circleY: 100,
isDragging: false,
dragStartX: 0,
dragStartY: 0
};
},
computed: {
line() {
return this.pathPoints.map(p => `${p[0]},${p[1]}`).join(' ');
}
},
methods: {
handleMouseDown(event) {
this.isDragging = true;
this.dragStartX = event.clientX;
this.dragStartY = event.clientY;
},
handleMouseMove(event) {
if (this.isDragging) {
const deltaX = event.clientX - this.dragStartX;
const deltaY = event.clientY - this.dragStartY;
const { x, y } = this.getNearestPoint(
this.circleX + deltaX,
this.circleY + deltaY
);
this.circleX = x;
this.circleY = y;
}
},
handleMouseUp(event) {
this.isDragging = false;
},
getNearestPoint(cx, cy) {
const distances = this.pathPoints.map(p => {
const dx = cx - p[0];
const dy = cy - p[1];
return Math.sqrt(dx * dx + dy * dy);
});
const index = distances.indexOf(Math.min(...distances));
return {
x: this.pathPoints[index][0],
y: this.pathPoints[index][1]
};
}
}
};
</script>
<style>
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.line {
stroke-width: 3;
}
</style>
```
这段代码绘制了一个简单的折线,并在折线上放置了一个可拖动的圆形元素。你可以将`pathPoints`数组中的值改为你需要绘制的折线点的坐标,也可以修改样式来适应你自己的设计。
阅读全文