It seems like you may be encountering difficulties in obtaining the correct mouse coordinates.
To ensure accuracy, consider utilizing getBoundingClientRect to retrieve them correctly.
var mousePos = [-1, -1];
var canvasRect, canvasLeft, canvasTop;
function updateCanvasRect() {
canvasRect = canvas.getBoundingClientRect();
canvasLeft = canvasRect.left;
canvasTop = canvasRect.top;
}
function updateMousePos(e) {
mousePos[0] = e.clientX - canvasLeft;
mousePos[1] = e.clientY - canvasTop;
}
If you are not using width/height in CSS to scale the canvas, the formula would be appropriate.
Remember to call
updateCanvasRect
after the document has loaded, and then again on scroll if scrolling is permitted.