I have an array of objects. Every object represents a square that's being drawn on the screen - x/y for placement and s for size, c for color).
const elements = [
{ x: 0, y: 0, s: 20, c: 'red' },
{ x: 110, y: 55, s: 7, c: 'blue' },
{ x: 250, y: 250, s: 50, c: 'green' },
{ x: 400, y: 400, s: 30, c: 'pink' }
]
That's how those would look on a canvas or just the page (doesn't have to be canvas really):
Now Imagine I have a 25x25px black square that is rendered instead of my cursor. When I move cursor over one of the colourful squares - so the square is fully covered - my pointer "eats" them up, so they disappear from the array and the canvas. Just like eating food in good old snake!
const pointer = { x: event.pageX, y: event.pageY, s: 25, c: 'black' }
So doing this:
Would remove elements[1] aka { x: 110, y: 55, s: 7, c: 'blue' }. As my cursor covers the whole blue square. I can't obviously eat up the green square as it's bigger than my cursor.
My question is - what's the best algorithm to find what items in my elements array are fully covered by the cursor considering I could have a lot of colourful squares (let's say over 1000)?
I've been trying to filter the covered item like so:
let squareCovered = elements.filter(square => square.x == pointer.x && square.y == pointer.y);
But this is not good enough as does not take both squares and cursors sizes, so I always have to put the cursor exactly at the very center of the square. When I'm trying to introduce sizes in this filtering method my project gets really laggy very fast.
Any hints? Is there a performant algorithm for this?
Feel free to edit the question title, no idea what I'm actually asking for.