MPe
MPe

Reputation: 430

Calculate the distance the mouse is moved during mouse button is pressed

I try to move an element in a canvas by the distance the mouse is moved while the mouse button is pressed.

    $("#hdr").on("mousemove", function(e) {
        console.log(e);
        if (e.which == 1) {
            console.log(e.pageX + " / " + e.pageY + "//" + e.offsetY +" / "+ e.offsetX);
        }
    });

It is no problem to get the recent mouse position, but I do not know how to store the initial mouse position, to calculate the moved distance.

Upvotes: 0

Views: 1581

Answers (1)

onx2
onx2

Reputation: 126

You can set a variable with the values you need. When the mouse button is pressed, store the value of this location and use that as a reference in your mousemove event to calculate distance. You can also store whether the mouse button is currently down or up if you'd like to only calculate distance while it is being held down.

jsfiddle: https://jsfiddle.net/xpvt214o/976224/

const mouseReference = {
    buttonDown: false,
    x: false,
    y: false
}

$('#hdr').on('mousedown', function (e) {
    mouseReference.buttonDown = true
    mouseReference.x = e.pageX
    mouseReference.y = e.pageY
}).on('mouseup', function (e) {
     mouseReference.buttonDown = false
}).on('mousemove', function (e) {
    if (e.which === 1 &&  mouseReference.buttonDown) {
    // The location (x, y) the mouse  was originally pressed
    console.log('refernce x: ', mouseReference.x)
    console.log('refernce y: ', mouseReference.y)

    // The new location of the mouse while being moved
    console.log('new x: ', e.pageX)
    console.log('new y: ', e.pageY)

    // Calculate distance here using the e.pageX / e.pageY and reference location
    }
})

EDIT: A slightly more concise way to write it by combining events (mousedown and mouseup) and reversing the boolean value on each event.

$('#hdr').on('mousedown mouseup', function (e) {
    mouseReference.buttonDown = !mouseReference.buttonDown
    mouseReference.x = e.pageX
    mouseReference.y = e.pageY
}).on('mousemove', function (e) {
    if (e.which === 1 &&  mouseReference.buttonDown) {
    // The location (x, y) the mouse  was originally pressed
    console.log('refernce x: ', mouseReference.x)
    console.log('refernce y: ', mouseReference.y)

    // The new location of the mouse while being moved
    console.log('new x: ', e.pageX)
    console.log('new y: ', e.pageY)

    // Calculate distance here using the e.pageX / e.pageY and reference location
    }
})

Upvotes: 2

Related Questions