在画布上跟踪鼠标移动时的奇怪行为

Odd behavior when tracking mouse movement on canvas

本文关键字:移动 跟踪 鼠标      更新时间:2023-09-26

我使用一个简单的脚本用鼠标在画布上画一条线。当用户在画布中单击和拖动时,它应该在该区域中绘制。这条线确实画好了,但它没有跟随鼠标,而且似乎不是偏移问题。按住按钮的时间越长,线条离光标的距离就越远。它画的线比我要求的要多,我不明白为什么。例如,如果我从画布的中心开始并向底部移动,那么这条线将在光标之前很久到达底部。这是我正在使用的代码:

if(window.addEventListener) {
window.addEventListener('load', function () {
  function init () {
    front_canvas = document.getElementById('front_paint_canvas');
    front_context = front_canvas.getContext('2d');
    tool = new tool_pencil();
    front_canvas.addEventListener('mousedown', ev_canvas, false);
    front_canvas.addEventListener('mousemove', ev_canvas, false);
    front_canvas.addEventListener('mouseup',   ev_canvas, false);
  }
  function tool_pencil () {
    var tool = this;
    this.started = false;
    this.mousedown = function (ev) {
        context.beginPath();
        context.moveTo(ev.clientX - 230, ev.clientY - 280);
        tool.started = true;
    };
    this.mousemove = function (ev) {
      if (tool.started) {
        context.lineTo(ev.clientX - 230, ev.clientY - 280);
        context.stroke();
      }
    };
    this.mouseup = function (ev) {
      if (tool.started) {
        tool.mousemove(ev);
        tool.started = false;
      }
    };
  }
  function ev_canvas (ev) {
      context = ev.target.getContext('2d');
    var func = tool[ev.type];
    if (func) {
      func(ev);
    }
  }
  init();
}, false); }

这怎么会发生?

您的上下文可能与画布大小不同。为了确保两者对齐,请使用此

front_canvas.width = front_canvas.clientWidth;
front_canvas.height = front_canvas.clientHeight;

就在创建上下文之前。

我想明白了。我把画布大小放在css中,而不是作为元素属性。这导致画布缩放,而不是简单地调整大小,这意味着它将线条绘制作为相对坐标而不是绝对坐标。