接收鼠标拖动的坐标

时间:2017-05-13 18:20:26

标签: javascript html5 canvas mouseevent

我想获得鼠标拖动的坐标。 我有画布,在我想要得到新鼠标(像素)的坐标抓住对象之后我画了同样的对象, 我的代码是在javascript中。 我的对象不是标签的html元素只是用像素画在画布里面,我想用鼠标抓住他,需要新的鼠标协调。

谢谢,

1 个答案:

答案 0 :(得分:1)

Canvas是一种2D图像元素/标签,因此没有直接的方法来拖动画布内的对象。

您需要在画布内侦听鼠标事件,并根据这些事件重新绘制画布 听这3个事件拖动画布内的对象

function handleMouseDown(e) {
    var mousePos = getMousePosition(canvas, e);
    // if current position matches the object postion
    // set a flag and monitor mouse move and mouse up event  
}
function handleMouseUp(e) {
    var mousePos = getMousePosition(canvas, e);
    //if your flag is true, then move the object to here and reset flag
}
function handleMouseMove(e) {
    var mousePos = getMousePosition(canvas, e);
    //Handle if you need smooth drag experience
}
function getMousePosition(canvas, e) {
   var boundary = canvas.getBoundingClientRect();
    // (e.clientX, e.clientY)  => Mouse coordinates wrt whole browser
    //  (boundary.left, boundary.top) => Canvas starting coordinate
    return {
      x: e.clientX - boundary.left,  
      y: e.clientY - boundary.top
    };
}
var canvas = document.getElementById('canvasId');
canvas.addEventListener('mousemove', handleMouseMove, false);
canvas.addEventListener('mousedown', handleMouseDown, false);
canvas.addEventListener('mouseup', handleMouseUp, false);