I have been trying to develop a drawing application. When I try to plot a point for freehand drawing, the point appears a good 100 or so pixels away from the actual position of the mouse pointer. Is there any way I can get the exact position of the mouse? You can see and run the code below.
const canvasEle = document.getElementById('drawContainer');
const context = canvasEle.getContext('2d');
function setMousePosition (e) {
var x = e.clientX;
var y = e.clientY;
console.log("x coord " + x + " y coord " + y);
changePixelColor(x, y)
}
function changePixelColor (x, y) {
context.fillRect(x,y,1,1);
}
canvasEle.addEventListener("mousemove", setMousePosition)
canvas {
border: 1px solid black;
width: 500px;
height: 500px;
position: absolute;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Draw</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="drawContainer"></canvas>
</body>
<script src="app.js"></script>
</html>