0

I have a HTML5 canvas in a document. Over that canvas some divs may be, hiding the canvas behind them (but still part of canvas is visible).

Knowing the position of canvas how can I check which divs actually cover the canvas so that I no longer draw behind those divs in order to improve perfromance?

And how do I actually only draw part of canvas to save some processing power?

Andrew Barber
  • 39,603
  • 20
  • 94
  • 123
XCS
  • 27,244
  • 26
  • 101
  • 151

1 Answers1

1

To determine if there is overlap:

var divid = document.getElementById ("myDiv");
var canvasid = document.getElementById ("myCanvas");

var div = divid.getBoundingClientRect();
var canvas = canvasid.getBoundingClientRect();

var overlap = !(div.right < canvas.left || 
                div.left > canvas.right || 
                div.bottom < canvas.top || 
                div.top > canvas.bottom);

To prevent drawing underneath a layered div, I would use those left/right/top/bottom offsets in your drawing on the canvas.

David Houde
  • 4,835
  • 1
  • 20
  • 29
  • I don't know which divs may be on top, I guess I have to check this for all divs (that don't have parents). What about browser support of boundingClientRect? And I actually to know which areas of the canvas are hidden, so there may only a corner be hidden, not the entire canvas. – XCS Feb 15 '13 at 20:52
  • You could check each div, but if it is only corners don't you think checking would create more overhead that just drawing? Not to mention your drawing paths would have to be re-worked to compensate. Without knowing the details of your project, I would say just cover the things up =] – David Houde Feb 15 '13 at 21:00
  • should be compatible with all browsers, not 100% of every method – David Houde Feb 15 '13 at 21:02
  • The canvas is drawn at 60fps/second and the overlapping is only checked once, so it is much better not to draw what users will not see anyway as drawing consumes A LOT of processing power. – XCS Feb 15 '13 at 22:23