Set Event Offset Coordinates Compatibly Cross-Browser

This method was born out of a frustrating discovery I made when playing with HTML5 Canvas. I found that Firefox had issues interpreting the X and Y locations of the mouse when drawing or placing elements on the canvas. So far I've had awesome, uniform results cross-browser by incorporating this as a utility method for canvas apps.

                                function setEventOffset(e){
	// target is for most browsers, srcElement is for IE
    var target = e.target || e.srcElement; 
	// get boundaries for surrounding element, canvas
    var rect = target.getBoundingClientRect();

	// Override event's offsetX and offsetY to the mouse 
	// location in the browser window, making sure to 
	// subtract the coordinates of the canvas element
    e.offsetX = e.clientX - rect.left;
    e.offsetY = e.clientY - rect.top;
}
                            

Here is an simple example of how to effectively make use of it. This method uses the mouse event's X and Y coordinates to draw a 10 pixel dot on the canvas when the mouse button is pressed down. In order to casually use offsetX and offsetY, just pass the event through to "sanitize" them for maximum compatibility.

                                var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

var drawPoint = function(e){
    // send event off to have offsets sanitized
    setEventOffset(e);

    ctx.beginPath();
	// use offsetX and offsetY without fear
    ctx.arc(e.offsetX, e.offsetY, 10, 0, Math.PI * 2);
    ctx.fill();
}

canvas.addEventListener('mousedown', drawPoint);