1

I know there is this question which suggests looping through all canvas elements on each mouse move.

However, is there a more effective way than looping through all the elements?

I have quite a few elements on the canvas and looping through them all on each mouse move could be very, very slow.

Community
  • 1
  • 1
Flot2011
  • 4,601
  • 3
  • 44
  • 61
  • Element means something quite specific in HTML, it seems from other comments you're not using element in this sense in your question. A `canvas` is an element, it doesn't *have* elements, it's just a bitmap. If you want your drawing to be made up of elements, use SVG. – robertc Oct 09 '12 at 13:27

2 Answers2

2

Yes, you have to loop through all of your elements.

That's how nearly all hit testing/object picking works.

Now there are a lot of optimizations you can do, like making sure that the mouse coordinate is in the rectangular bounds of the object before you test its real bounds (unless they're all rectangles, which would make everything convenient and fast, even if there are 10,000 objects). If you have a million objects, you could also split up their location into quadrants, or otherwise add a layer of isolation.

But at the end of the day you need to loop through every relevant object and ask if its bounds intersect the mouse point. There's no way of getting around that. It ought to be fast, and if you've implemented something that is very slow then you should post it so we can take a look and give you pointers.

If you need to see a live example I made a simple tutorial on picking and moving shapes in a canvas exactly for explaining situations like this.

Simon Sarris
  • 62,212
  • 13
  • 141
  • 171
  • Thank you Simon, it's with your excellent tutorial that I started to learn HTML5 canvas a while ago. I suppose what I am using now you would have called quadrants. I divided the canvas on some areas, table-like, and I am going through this table to define the correct "cell". But what do you mean by "layer of isolation"? – Flot2011 Oct 10 '12 at 07:49
0

Looping through 10000 of elements is still no effort in javascript.

However you might consider looping throught them with some interval not on every mousemove.

var mouseX, mouseY;

$(document).on("mousemove", function(e) {
  mouseX = e.pageX;
  mouseY = e.pageY;

  /* dont do any probing there */

});

setInterval(function() {
  checkCollision();
}, 25);
rezoner
  • 1,907
  • 13
  • 16