我正在创建绘图应用,由于某种原因,控制台无法识别clientX
和clientY
我尝试在Chrome上禁用设备模式,但错误仍然存在
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Canvas</title>
<link href="canvas.css" rel="stylesheet">
</head>
<body>
<div id="container">
<canvas id="canvas"></canvas>
</div>
</body>
<script src="canvas.js"></script>
</html>
#canvas{
border: 1px solid black;
}
#container{
text-align: center;
}
window.addEventListener('load', () => {
const canvas = document.querySelector("#canvas");
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
const ctx = canvas.getContext("2d");
let painting = false;
function startPosistion(e){
painting = true;
draw(e);
}
function endPosistion(){
painting = false;
ctx.beginPath();
}
function draw(e){
if(!painting) return;
ctx.lineWidth = 10;
ctx.lineCap = 'round';
ctx.lineTo(e.clientX, e.clientY);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(e.clientX, e.clientY);
}
canvas.addEventListener('mousedown', startPosistion());
canvas.addEventListener('mouseup', endPosistion());
canvas.addEventListener('mousemove', draw);
});
我希望当用户按下鼠标时,会出现一行。当用户释放该行时,该行不再拖动。
答案 0 :(得分:2)
已更改
canvas.addEventListener('mousedown', startPosistion());
canvas.addEventListener('mouseup', endPosistion());
canvas.addEventListener('mousemove', draw);
到
canvas.addEventListener('mousedown', startPosistion);
canvas.addEventListener('mouseup', endPosistion);
canvas.addEventListener('mousemove', draw);