我是新手 konvas libray 用户,我尝试制作一个简单的游戏,我需要检测何时从形状中拖出盒子并显示警报“louser”,问题是形状不规则,因为检测事件的功能对矩形形状很好,但是在不规则形状中不尊重边框形式,我希望可以帮助我检测盒子何时拖出不规则形状并尊重边框,thankeyou,代码如下
Konva Drag and Drop Multiple Shapes Demoview raw
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/konva@7.2.2/konva.min.js"></script>
<meta charset="utf-8" />
<title>Konva Drag and Drop Collision Detection 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();
stage.add(layer);
var RectA = new Konva.Rect({
x: 380,
y:100,
width: 30,
height: 30,
fill: 'grey',
name: 'fillShape',
draggable: true,
stroke: 'red',
hitStrokeWidth: 30,
});
var RectB = new Konva.Line({
x: 350,
y: 80,
points:[0, 0, 50, 0, 50, 100, 0, 100],
fill: 'grey',
closed: true,
name: 'fillShape',
draggable: false,
stroke: 'red',
hitStrokeWidth: 10,
tension: 1,
});
layer.add(RectB);
layer.add(RectA);
layer.draw();
RectA.on('dragmove', function (e) {
var target = e.target;
var targetRect = e.target.getClientRect();
layer.children.each(function (RectB) {
// do not check intersection with itself
if (RectB === target) {
return;
}
if (haveIntersection(RectB.getClientRect(), targetRect)) {
// RectB.findOne('.fillShape').fill('red');
} else {
alert("louse");
// RectB.findOne('.fillShape').fill('grey');
}
// do not need to call layer.draw() here
// because it will be called by dragmove action
});
});
function haveIntersection(r1, r2) {
return !(
r2.x > r1.x + r1.width ||
r2.x + r2.width < r1.x ||
r2.y > r1.y + r1.height ||
r2.y + r2.height < r1.y
);
}
layer.draw();
</script>
</body>
</html>