Finding Relative Mouse Position

21 views
Skip to first unread message

Wayne Holder

unread,
Nov 16, 2015, 12:43:38 PM11/16/15
to Google Caja Discuss
I'm trying to use an "HTML Box" in Google Sites to publish a canvas-based program that needs to find the mouse position relative to the canvas.  I'm posting here because the Google Sites HTML Box feature seems to use Caja as the canvas gets embedded in a tag named "<caja-v-body>" when I view the page source in the browser.  The problem is that I can't find a way to determine the offset to the canvas when my code is embedded in an HTML Box, so I am therefore unable to compute the mouse position relative to the canvas.  The closest I've been able to get is to use code like this:

        var obj = canvas;
        var top = 0;
        var left = 0;
        if (obj.offsetParent) {
          do {
            left += obj.offsetLeft;
            top += obj.offsetTop;
          } while (obj = obj.offsetParent);
        }

to try and add up the list of offsets.  However, this code only seems to chain back two levels and therefore can't determine all the offsetting elements on the complete page.  I've also tried numerous other approaches to find the offset to the canvas, such as calling canvas.getBoundingClientRect() to get the offset, but this also fails to account for all the active offsets.  Note: this code works fine when it's not embedded in an HTML Box.

Not being able to get the event position relative to the canvas makes it rather hard to write any kind of mouse event code, so I'm hoping there is some type of workaround I can use.

Wayne
Reply all
Reply to author
Forward
0 new messages