vue konva在已有的多个rect增加鼠标移动进去提示
时间: 2023-08-09 15:04:25 浏览: 157
要在已有的多个Konva矩形上增加鼠标移动进入提示,可以使用循环遍历每个矩形,并为其添加事件监听器和tooltip。
首先,创建一个数组来存储所有的矩形对象:
```
data() {
return {
rects: [
{id: 1, x: 10, y: 10, width: 50, height: 50},
{id: 2, x: 70, y: 10, width: 50, height: 50},
{id: 3, x: 130, y: 10, width: 50, height: 50}
]
}
}
```
然后,在Konva的mounted生命周期钩子中,使用循环遍历每个矩形,并为其添加事件监听器和tooltip:
```
mounted() {
var layer = new Konva.Layer();
this.$refs.stage.getStage().add(layer);
for (var i = 0; i < this.rects.length; i++) {
var rect = new Konva.Rect({
x: this.rects[i].x,
y: this.rects[i].y,
width: this.rects[i].width,
height: this.rects[i].height,
fill: 'red'
});
layer.add(rect);
rect.on('mouseover', function() {
var tooltip = new Konva.Label({
opacity: 0.75,
visible: false,
listening: false
});
tooltip.add(new Konva.Tag({
fill: 'black',
pointerDirection: 'down',
pointerWidth: 10,
pointerHeight: 10,
lineJoin: 'round',
shadowColor: 'black',
shadowBlur: 10,
shadowOffset: 10,
shadowOpacity: 0.5
}));
tooltip.add(new Konva.Text({
text: 'Tooltip Text',
fontFamily: 'Calibri',
fontSize: 18,
padding: 5,
fill: 'white'
}));
layer.add(tooltip);
tooltip.position({
x: rect.x(),
y: rect.y() - 20
});
tooltip.show();
tooltip.moveToTop();
});
}
layer.draw();
}
```
在事件监听器中,使用变量rect来引用当前矩形对象,而不是使用this关键字。这是因为在循环中,this关键字引用的是循环的上下文,而不是当前矩形对象。
完整的代码示例:
```
<template>
<div>
<v-stage ref="stage" :config="stageSize">
<v-layer></v-layer>
</v-stage>
</div>
</template>
<script>
import Konva from 'konva';
export default {
data() {
return {
stageSize: {
width: 200,
height: 100
},
rects: [
{id: 1, x: 10, y: 10, width: 50, height: 50},
{id: 2, x: 70, y: 10, width: 50, height: 50},
{id: 3, x: 130, y: 10, width: 50, height: 50}
]
}
},
mounted() {
var layer = new Konva.Layer();
this.$refs.stage.getStage().add(layer);
for (var i = 0; i < this.rects.length; i++) {
var rect = new Konva.Rect({
x: this.rects[i].x,
y: this.rects[i].y,
width: this.rects[i].width,
height: this.rects[i].height,
fill: 'red'
});
layer.add(rect);
rect.on('mouseover', function() {
var tooltip = new Konva.Label({
opacity: 0.75,
visible: false,
listening: false
});
tooltip.add(new Konva.Tag({
fill: 'black',
pointerDirection: 'down',
pointerWidth: 10,
pointerHeight: 10,
lineJoin: 'round',
shadowColor: 'black',
shadowBlur: 10,
shadowOffset: 10,
shadowOpacity: 0.5
}));
tooltip.add(new Konva.Text({
text: 'Tooltip Text',
fontFamily: 'Calibri',
fontSize: 18,
padding: 5,
fill: 'white'
}));
layer.add(tooltip);
tooltip.position({
x: rect.x(),
y: rect.y() - 20
});
tooltip.show();
tooltip.moveToTop();
});
}
layer.draw();
}
}
</script>
```
阅读全文