The problem is:
We have a big canvas (with scroll) inside a div, with a background image, and if we try to draw over it coordinates are not the same.
To show the problem we draw in the mousemove function, the position is ok at 0,0 coordinates but if we keep moving to the right or down in the image the difference the circle is draw and mouse is bigger and bigger.
If mouse is near top left corner difference where circle is paint is little but if we are near bottom right difference is several hundred of pixels.
The canvas inside a a div:
<canvas style="width: 1500px; height:800px;" id="myImage" width="1947" height="949"></canvas>
Style is to fix a size and get scroll, width and height is the image real size.
canvas = document.getElementById('myImage');
context = canvas.getContext('2d');
s.addEventListener('mousemove', function(evt) {
var mousePos = getMousePos(canvas, evt);
drawTest(mousePos.x, mousePos.y);
}, false);
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
function drawTest(centerX, centerY) {
//var rect = canvas.getBoundingClientRect();
//centerX = centerX + rect.left;
//centerY = centerY + rect.top;
var radius = 5;
context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'green';
context.fill();
context.lineWidth = 2;
context.strokeStyle = '#003300';
context.stroke();
}
We've tried with, and without, adding canvas.getBoundingClientRect
coordinates with no result.
Question
How can we solve it and draw in the same exact coordinate the mouse is?