folk-canvas/demo/collision.html

76 lines
1.9 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Shapes - Collision</title>
<style>
* {
box-sizing: border-box;
}
html {
height: 100%;
}
body {
min-height: 100%;
position: relative;
margin: 0;
}
fc-geometry {
border: 2px solid black;
}
</style>
</head>
<body>
<fc-geometry x="100" y="100" width="50" height="50"></fc-geometry>
<fc-geometry x="200" y="200" width="50" height="50"></fc-geometry>
<script type="module">
import { FolkGeometry } from '../src/canvas/fc-geometry.ts';
FolkGeometry.register();
const geometryElements = document.querySelectorAll('fc-geometry');
function collisionDetection(rect1, rect2) {
return (
rect1.left < rect2.right &&
rect1.right > rect2.left &&
rect1.top < rect2.bottom &&
rect1.bottom > rect2.top
);
}
function handleCollision(e) {
geometryElements.forEach((el) => {
if (
el !== e.target &&
collisionDetection(
// TODO: refactor this hack once resizing and the vertices API are figured out
DOMRectReadOnly.fromRect({
x: el.x,
y: el.y,
height: el.height,
width: el.width,
}),
DOMRectReadOnly.fromRect({
x: e.target.x,
y: e.target.y,
height: e.target.height,
width: e.target.width,
})
)
) {
e.preventDefault();
}
});
}
document.addEventListener('move', handleCollision);
document.addEventListener('resize', handleCollision);
</script>
</body>
</html>