在一个vue文件中,使用svg画出路径d: path("M20,80 L50,20 L80,80"),并实现小方块在此路径上拖动
时间: 2024-06-07 10:05:19 浏览: 160
很高兴回答这个问题!首先,要在vue文件的template中使用svg来呈现路径d的效果,代码如下:
<template>
<svg>
<path :d="path" stroke="black" fill="none"></path>
<rect ref="rect" x="20" y="70" width="10" height="10" fill="red" @mousedown="startDrag" />
</svg>
</template>
接下来,我们需要在vue文件的script中定义路径d的值以及拖动小方块的逻辑。代码如下:
<script>
export default {
data() {
return {
path: "M20,80 L50,20 L80,80",
dragging: false,
startX: 0,
startY: 0
};
},
methods: {
startDrag(e) {
this.dragging = true;
this.startX = e.clientX;
this.startY = e.clientY;
window.addEventListener("mousemove", this.dragRect);
window.addEventListener("mouseup", this.stopDrag);
},
dragRect(e) {
if (this.dragging) {
const dx = e.clientX - this.startX;
const dy = e.clientY - this.startY;
const rect = this.$refs.rect;
const path = this.$el.querySelector("path");
const len = path.getTotalLength();
const { x, y } = this.getPathPosition(len, dx, dy);
rect.setAttribute("x", x);
rect.setAttribute("y", y);
}
},
stopDrag() {
this.dragging = false;
window.removeEventListener("mousemove", this.dragRect);
window.removeEventListener("mouseup", this.stopDrag);
},
getPathPosition(len, dx, dy) {
const { x, y } = this.$refs.rect.getBBox();
const pos = path.getPointAtLength(len * ((30 - y) / 60));
const angle = Math.atan2(pos.y - y, pos.x - x);
return {
x: pos.x + dx + 5 * Math.cos(angle),
y: pos.y + dy + 5 * Math.sin(angle)
};
}
}
};
</script>
这样,就实现了小方块在路径上拖动的效果。希望这个回答可以帮到你!
阅读全文