How to detect collision with JS

I’m making my first game in canvas+javascript, simple space shooter. The problem is that I use two nested for loops to check if rocket hits the enemy like this:


and this causes small but still annoying lag. I was researching this here and on google but nobody seems to bother with that since we have different engines for this. Does anybody know how do solve this problem without nested for loops?

  • Why does filling in a rectangle on a canvas degrade performance slowly?
  • Does canvas drawing work in Ionic 2?
  • Render HTML in Canvas/WebGL
  • Building an Image Editor with HTML 5 and Canvas
  • Uploading 'canvas' image data to the server
  • collision detection between a disk and an vertical rectangle
  • Thanks for answer!

  • WebGL Multiple Canvas three.js example
  • HTML5 drawing pictures on a canvas with a for loop?
  • html5 canvas clicking on bezier path shape detection
  • looking for algorithm to find boundary of color region
  • How do I add a simple onClick event handler to a canvas element?
  • Draw a Square on the HTML5 Canvas With Touch Events
  • One Solution collect form web for “How to detect collision with JS”

    You could either use a multidimensional array of “tiles” or a hash table where the key is the x and y position. On a “collision” in the data structure, you trigger your event for your collision.