To get the javascript code in my previous post to work correctly while logged in to WordPress I had to put in a ‘hack’ that checked for the presence of the admin bar and accounted for its height when calculating mouse coordinates. I was asked why this was necessary, and I didn’t have a very good answer… I just knew that the presence of the admin bar made a certain value 28px too large. But I have a better answer now:
The problem is that the admin bar includes the following css:
html {
margin-top:28px !important;
}
The admin bar is then placed in the margin with position: fixed, which is what causes it to stay at the top of the page even after you scroll. This margin is a problem because we need two values to calculate the position of a mouse click relative to the canvas: the mouse event’s pageX/pageY coordinates, and the canvas element’s offsets (top and left). The two canvas offsets are relative to the body element, so the margin, which is outside of the body, doesn’t affect this number. However pageX/pageY are relative to the entire document, which includes that additional margin. So if the admin bar is present, pageY will be 28px larger than we expect it to be.