标题: 禁用监听形状提示

您可以将 listening(false) 设置为形状,以从命中图中移除它。这意味着该形状将在命中检测中不可见(尽管在画布上可见),因此它不会触发任何鼠标或触摸的交互。同时,这样的节点将在 container.getIntersection()container.getAllIntersections() 方法中被忽略。

listening(false) 设置为节点将提高性能。

例如,我们有一个按钮(组),包含一个矩形和文本。我们需要监听按钮的点击事件。在这种情况下,我们可以将文本从命中图中移除,仅监听矩形的点击事件。

Konva 禁用监听形状示例view raw
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/konva@9.3.18/konva.min.js"></script>
<meta charset="utf-8" />
<title>Konva Listening False Demo</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #f0f0f0;
}
</style>
</head>
<body>
<div id="container"></div>
<script>
var width = window.innerWidth;
var height = window.innerHeight;

var stage = new Konva.Stage({
container: 'container',
width: width,
height: height,
});
var layer = new Konva.Layer();

var button = new Konva.Group({
x: stage.width() / 2,
y: stage.height() / 2,
});

var offset = 10;
var text = new Konva.Text({
x: offset,
y: offset,
text: 'press me!',
// as we don't really need text on hit graph we can set:
listening: false,
});
var rect = new Konva.Rect({
width: text.width() + offset * 2,
height: text.height() + offset * 2,
fill: 'grey',
shadowColor: 'black',
});
button.add(rect, text);

button.on('click tap', function () {
alert('button clicked');
});

layer.add(button);
stage.add(layer);
</script>
</body>
</html>