用JavaScript在鼠标中心下方绘制的线



我正在使用JavaScript开发一个简单的绘图工具。但是,我的draw()函数有问题。该线始终绘制在鼠标中心的稍下方。我可以知道我在这里犯了什么错吗?我希望在鼠标移动时始终将线绘制在鼠标的中心。在我的setPosition()函数中,e.pageXe.pageY是否真的将鼠标中心映射为xy坐标?

<!doctype html>
<html>
<head>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<div class="controls">
<button class="clear">Clear</button> <span>Color
<input type="color" value="#ffff00" id="penColor"></span>
<span>Width
<input type="range" min="1" max="20" value="10" id="penWidth"></span>
</div>
<canvas id="canvas"></canvas>
<script>
let penColor = document.getElementById("penColor");
let penWidth = document.getElementById("penWidth");
let canvas = document.getElementById("canvas");
canvas.width = 700;
canvas.height = 700;
let context = canvas.getContext("2d");
let clearButton = document.querySelector(".clear");
let position = {
x: null,
y: null
}
let initialization = (e) => {
canvas.addEventListener("mousemove", draw);
canvas.addEventListener("mouseenter", setPosition)
canvas.addEventListener("mousemove", setPosition)
}
window.onload = initialization;
let setPosition = (e) => {
position.x = e.pageX;
position.y = e.pageY;
}
clearButton.addEventListener("click", (e) => {
let confirmation = confirm("Are you sure you want to clear the canvas?");
let result = confirmation ? true : false;
if (result) {
context.clearRect(0, 0, canvas.width, canvas.height);
}
})

let draw = (e) => {
if (e.buttons !== 1) return;
context.beginPath();
context.moveTo(position.x, position.y);
setPosition(e);
context.lineTo(position.x, position.y);
context.lineWidth = penWidth.value;
context.strokeStyle = penColor.value;
context.lineCap = "round";
context.stroke();
}
</script>
</body>
</html>

鼠标事件.pageX

MouseEvent界面的pageX只读属性返回鼠标单击时相对于整个文档左边缘的X(水平(坐标(以像素为单位(。

https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/pageX

所以这不是画布上的X位置,你必须减去画布的位置。

e.pageX - canvas.offsetLeft;
e.pageY - canvas.offsetTop;

let canvas = document.getElementById("canvas");
canvas.width = canvas.height = 200;
let context = canvas.getContext("2d");
let position = { x: null, y: null }
let setPosition = (e) => {
position.x = e.pageX - canvas.offsetLeft;
position.y = e.pageY - canvas.offsetTop;
}
let draw = (e) => {
if (e.buttons !== 1) return;
context.beginPath();
context.moveTo(position.x, position.y);
setPosition(e);
context.lineTo(position.x, position.y);
context.stroke();
}
canvas.addEventListener("mousemove", draw);
canvas.addEventListener("mouseenter", setPosition)
canvas.addEventListener("mousemove", setPosition)
canvas {
border: 1px solid black;
}
<canvas id="canvas"></canvas>

最新更新