画布拖动鼠标移动

画布拖动鼠标移动

本文介绍了画布拖动鼠标移动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个可以使用鼠标移动来拖动的画布.我做错了一些我无法理解的错误,起初似乎可以解决问题,然后又出现了一个增量错误,使画布移动得太快.

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.

考虑以下代码,

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()
    }

  })

}

Plunker上的实时示例 https://plnkr.co/edit/j8QCxwDzXJZN2DKszKwm .

live example on Plunker https://plnkr.co/edit/j8QCxwDzXJZN2DKszKwm.

有人可以帮助我了解我缺少的东西吗?

Can someone help me to understand what piece I'm missing?

推荐答案

您的代码有问题,因为:

Your code is having problem, because:

每次您要相对于dragStart位置移动矩形blablabla px,但是 translate()方法不是基于dragStart位置,而是基于当前位置.

Each time you want to move the rectangle blablabla px relative to the dragStart position, yet the translate() method is not based on dragStart position, but your current position.

要解决此问题,应在调用 translate 方法后添加以下内容:

To fix this, you should add the following after calling the translate method:

dragStart = dragEnd;

因此您的位置也基于当前的鼠标位置.

So that your position is also based on current mouse position.

这篇关于画布拖动鼠标移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 12:23