I’m making a small online multiplayer game with JavaScript and the native Canvas API (WebGL). I want to find the color of pixels on the screen as a form of collision detection, I figure it’d save resources to not have to process every shape every frame, but rather to simply check if the color of a pixel at a certain position is such that it is contacting a shape. (I hope that makes sense)
I ran some tests and I have an average frame delay of about 4-5 milliseconds without collision detection, and then when I make a single call to my canvas context’s .getImageData()
method, suddenly that frame delay shoots up to 19-20 milliseconds…
As far as I can find online getImageData()
is the only means of checking the color of a given pixel, but I have to think there’s some other way that doesn’t introduce such a huge amount of lag.
I tried running getImageData()
on a small section of the screen vs larger sections, and a 1×1 pixel request introduces 10ms latency, where a 600×600 pixel request is about 15ms… So the issue isn’t the amount/size of the request, but rather just the request itself is extremely slow, so there’s no potential for optimization here, I NEED another way.
Also, caching the image data is also not an option. I need to poll these pixels every single frame, I can’t cache it (because the player and the object it needs to collide with are all constantly moving, and they’re being controlled over the internet so there’s also no way of predicting where they’ll be at any given time… I NEED to poll every frame with no exceptions)