I am trying to build a simple app in which the user drags a word onto the corresponding image. When the user "drops" the word on the image a collision needs to be detected. I have a console.log message which should only log when this happens. Currently my message is logging even when there is no collision. Any ideas where I'm going wrong? Here is my code:
//create stage to hold the text and image canvases
var stage = new Konva.Stage({
container: 'container',
width: window.innerWidth,
height: window.innerHeight,
});
//*************************************** IMG CANVAS *************************************/
// // add img canvas element
var imgLayer = new Konva.Layer();
stage.add(imgLayer);
var imageObj = new Image();
imageObj.onload = function () {
var item = new Konva.Image({
x: 200,
y: 200,
image: imageObj,
width: 400,
height: 400,
stroke: 'black',
});
// add the shape to the layer
imgLayer.add(item);
};
imageObj.src = 'assets/apple.jpg';
//*************************************** TEXT CANVAS *************************************/
// add text canvas element
var textLayer = new Konva.Layer();
stage.add(textLayer);
// create text
var text = new Konva.Text({
x: 350,
y: 0,
text: 'apple',
fontSize: 40,
fontFamily: 'Calibri',
fill: 'blue',
draggable: true,
});
textLayer.add(text);
// add text cursor styling
text.on('mouseover', function () {
document.body.style.cursor = 'pointer';
});
text.on('mouseout', function () {
document.body.style.cursor = 'default';
});
//************************************* COLLISION ***************************************/
text.on('dragend', (e)=>{
const target = e.target;
console.log(target);
const targetImg = imgLayer;
console.log(targetImg);
if (haveIntersection(target, imgLayer)) {
console.log("collision");
} else {
console.log('no collision');
}
});
const 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
);
}