I am writing some JavaScript code that should select a random element from the canvas if the element meets certain requirements. There are different objects (circles, triangles, squares, etc.), and usually not the same number of objects for each type. Elements are arranged in a hierarchy (therefore, a square may contain several circles, and a circle may contain other circles, etc. - all of them may be nested).
Right now, my (primitive) approach when choosing a random element is as follows:
- Cross the canvas recursively and build a (possibly huge!) List of items
- Shuffle the list
- Iterate the shuffled list in front until you find an item that satisfies some additional requirements.
The problem is that it does not scale well. I often run into memory problems because the recursion depth is too large or the general list of elements is getting too large.
I was thinking of rewriting this code so that I would consider the choice of elements while going through the canvas - but I don’t know how I could “accidentally” select an element if I don’t know how many elements there are in total.
Does anyone have any ideas how to solve this?
source
share