我正在尝试在浏览器中创建一个 javascript 绘图程序,但出现了错位。我的代码有问题吗?

I'm trying to make a javascript drawing program within the browser and things are misaligned. Is there something wrong with my code?

我已经在这个非常基本的绘图程序上工作了一段时间,但似乎无法让它正常工作。

用户现在可以在 canvas 元素中绘制,但有些地方错位了;当您尝试绘制时,线条看起来离光标很远,我不确定是什么原因造成的。

这是我的代码...

html

<div class="info">
    
  <canvas id="canvas" height="480" width="640" style="border:1px solid #000000; width: 640px; height:480px; background-color: white">Please update your browser.</canvas>
  <script src="paint.js"></script> 
    
</div>

javascript

// paint.js
(function () {
  var canvas = document.getElementById("canvas");
  var context = canvas.getContext("2d");

  //resizing
  //canvas.height = window.innerHeight;
  //canvas.width = window.innerWidth;

  //variables
  var painting = false;

  function startPosition(e) {
    painting = true;
    draw(e);
  }

  function endPosition() {
    painting = false;
    context.beginPath();
  }

  function draw(e) {
    if (!painting) return;
    context.lineWidth = 7;
    context.lineCap = "round";
    context.strokeStyle = "green";

    context.lineTo(e.clientX, e.clientY);
    context.stroke();
    context.beginPath();
    context.moveTo(e.clientX, e.clientY);
  }

  //EventListeners
  canvas.addEventListener("mousedown", startPosition);
  canvas.addEventListener("mouseup", endPosition);
  canvas.addEventListener("mousemove", draw);
})();

clientXclientY 更改为 offsetXoffsetY 以根据鼠标在元素内的位置获得正确的坐标

您可以阅读有关 MouseEvent 的更多信息并找出两者之间的区别

clientX/Y
screenX/Y
offsetX/Y

试试这个片段

// paint.js
(function () {
  var canvas = document.getElementById("canvas");
  var context = canvas.getContext("2d");

  //resizing
  //canvas.height = window.innerHeight;
  //canvas.width = window.innerWidth;

  //variables
  var painting = false;

  function startPosition(e) {
    painting = true;
    draw(e);
  }

  function endPosition() {
    painting = false;
    context.beginPath();
  }

  function draw(e) {
    if (!painting) return;
    context.lineWidth = 4;
    context.lineCap = "round";
    context.strokeStyle = "green";

    context.lineTo(e.offsetX, e.offsetY);
    context.stroke();
    context.beginPath();
    context.moveTo(e.offsetX, e.offsetY);
  }

  //EventListeners
  canvas.addEventListener("mousedown", startPosition);
  canvas.addEventListener("mouseup", endPosition);
  canvas.addEventListener("mousemove", draw);
})();
div {
  width: 460px;
  height: 460px;
  border: 1px solid black;
}
<div class="info">
    
  <canvas id="canvas" height="460" width="460" style="border:1px solid #000000; background-color: white">Please update your browser.</canvas>
  <script src="paint.js"></script> 
    
</div>