I want to create a line drawing effect with the mouse, which is similar to the line drawing function of the drawing board that comes with the window. This requires obtaining the coordinates of the mouse, but I always feel that the coordinates are not obtained accurately. Every time I draw a line on the canvas, the line is always drawn clearly below the cursor, not from the position of the cursor. Start drawing lines. If you draw a line at the bottom of the canvas and it cannot come out at all, the actual coordinate value obtained may exceed the size of the canvas. Is my method of obtaining coordinate values wrong? I would like to ask everyone!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
<style> body {
background: #000;
} </style>
<script> window.onload = function () {
var oC = document.getElementById('cav');
var ctx = oC.getContext('2d');
oC.onmousedown = function (evt) {
var x = evt.pageX - oC.offsetLeft;
var y = evt.pageY - oC.offsetTop;
ctx.moveTo(x, y);
oC.onmousemove = function (evt) {
var x = evt.pageX - oC.offsetLeft;
var y = evt.pageY - oC.offsetTop;
ctx.lineTo(x, y);
ctx.stroke();
}
oC.onmouseup = function () {
oC.onmousemove = null
}
}
} </script>
</head>
<body>
<canvas id="cav" style="width: 400px;height: 400px;background: white"></canvas>
</body>
</html>
Replaced with
The difference between width and height of canvas tag and style.width and style.height