简体   繁体   English

画布拖动鼠标移动

[英]Canvas drag on mouse movement

I'm trying to build a canvas that i can drag using mouse movement.我正在尝试构建一个可以使用鼠标移动拖动的画布。 And I'm doing something wrong that i cannot understand cause seems to work at first and then there is like an incremental error that make the canvas move too fast.而且我做错了一些我无法理解的事情,原因一开始似乎起作用,然后出现了一个增量错误,使画布移动得太快。

Considering the following code,考虑以下代码,

window.onload = function() {
  var canvas = document.getElementById("canvas");
  var context = canvas.getContext('2d');


  function draw() {
    context.fillRect(25, 25, 100, 100);
  }

  function clear() {
    context.clearRect(0, 0, canvas.width, canvas.height);
  }
  var drag = false;
  var dragStart;
  var dragEnd;
  draw()
  canvas.addEventListener('mousedown', function(event) {
    dragStart = {
      x: event.pageX - canvas.offsetLeft,
      y: event.pageY - canvas.offsetTop
    }

    drag = true;

  })

  canvas.addEventListener('mousemove', function(event) {
    if (drag) {
      dragEnd = {
        x: event.pageX - canvas.offsetLeft,
        y: event.pageY - canvas.offsetTop
      }
      context.translate(dragEnd.x - dragStart.x, dragEnd.y - dragStart.y);
      clear()
      draw()
    }

  })

}

live example on Plunker https://plnkr.co/edit/j8QCxwDzXJZN2DKszKwm . Plunker 上的现场示例https://plnkr.co/edit/j8QCxwDzXJZN2DKszKwm

Can someone help me to understand what piece I'm missing?有人可以帮助我了解我错过了什么吗?

The problem your code has is that each time you move the rectangle blablabla px relative to the dragStart position, the translate() method is not based on dragStart position, but your current position.您的代码存在的问题是,每次相对于 dragStart 位置移动矩形 blablabla px 时, translate()方法不是基于 dragStart 位置,而是基于您的当前位置。

To fix this, you should add the following after calling the translate method:要解决此问题,您应该在调用translate方法后添加以下内容:

dragStart = dragEnd;

So that your position is also based on current mouse position.这样您的位置也基于当前鼠标位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM