Last active
April 3, 2021 18:10
-
-
Save ThatOneBro/1c7ba9b3ffdbe9c3ee0be3c36398463f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const isPositionWithinBox = (point1, point2, coords) => { | |
| if (point1.x < coords.x && point2.x > coords.x && point1.y > coords.y && point2.y < coords.y) | |
| return true; | |
| return false; | |
| }; | |
| const getBoundingBox = (origin, width, height) => { | |
| const x1 = origin.x - width / 2; | |
| const y1 = origin.y + height / 2; | |
| const x2 = origin.x + width / 2; | |
| const y2 = origin.y - height / 2; | |
| return [ | |
| { x: x1, y: y1 }, | |
| { x: x2, y: y2 }, | |
| ]; | |
| }; | |
| const getMousePos = (canvas, evt) => { | |
| // It's a very reliable algorithm to get mouse coordinates (don't use anything else) | |
| // it works fine on Firefox and Chrome | |
| // source : https://stackoverflow.com/questions/17130395/real-mouse-position-in-canvas | |
| const rect = canvas.getBoundingClientRect(); | |
| return { | |
| x: ((evt.clientX - rect.left) / (rect.right - rect.left)) * canvas.width, | |
| y: ((evt.clientY - rect.top) / (rect.bottom - rect.top)) * canvas.height, | |
| }; | |
| }; | |
| const getRelMousePos = (canvas, evt) => { | |
| const { x, y } = getMousePos(canvas, evt); | |
| const origin = { x: canvas.width / 2, y: canvas.height / 2 }; | |
| return { x: (x - origin.x) / 10, y: -((y - origin.y) / 10) }; | |
| }; | |
| const shapeClicked = (evt, onClick) => { | |
| if (evt.target.nodeName.toLowerCase() !== 'canvas') return; | |
| const coords = getRelMousePos(evt.target, evt); | |
| const [p1, p2] = getBoundingBox({ x: -20, y: 3 }, 20, 13); | |
| if (isPositionWithinBox(p1, p2, coords)) { | |
| evt.stopPropagation(); | |
| onClick(evt); | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment