I have a tag within a HTML5 document.
How can I detect the distance with JavaScript from the top-left corner of the HTML page to the top left corner of the canvas tag?
I need to be able to position dynamically generated html tags relative to the canvas.
getBoundingClientRect()
is your friend and is supported in recent-ish versions (Firefox 3, Safari 4, Chrome, Opera 9.5, IE 5) of all browsers. It will give you coordinates relative to the viewport rather than the page, however, so you need to add on the document's scroll amounts:
function getPageTopLeft(el) {
var rect = el.getBoundingClientRect();
var docEl = document.documentElement;
return {
left: rect.left + (window.pageXOffset || docEl.scrollLeft || 0),
top: rect.top + (window.pageYOffset || docEl.scrollTop || 0)
};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With