Jezen Thomas
Jezen Thomas

Reputation: 13800

Updating position on drag

I'm trying to create a crude crop tool with JavaScript/jQuery. I have a HTML element with fixed dimensions and overflow:hidden that I’m using as my canvas. The user should be able to drag an image inside this element, to position the image to their liking within the crop boundaries.

I’m having a little trouble with calculating the correct offset.

I’ve set up a jsFiddle here: http://jsfiddle.net/YtyFH/

The part I’m having trouble with is:

if (drag) {
    $img.css({
        top: e.offsetY - this.offsetTop,
        left: e.pageX - this.offsetLeft
    });
}

Currently, when the user begins to drag inside the canvas, the edge of the image snaps to the cursor position. I’d like the image to begin moving from where it already is.

Upvotes: 0

Views: 201

Answers (1)

Brewal
Brewal

Reputation: 8189

This is a possible fix. See the Updated Fiddle

var $img = $this.find('img');
var offset = {
    left : $img.css('left') == 'auto' ? e.pageX : e.pageX - parseInt($img.css('left')),
    top : $img.css('top') == 'auto' ? e.pageY : e.pageY - parseInt($img.css('top'))
}

$this.on('mousemove', function (e) {
    if (drag) {
        $img.css({
        top: e.pageY - offset.top,
        left: e.pageX - offset.left
        });
    }
})

Upvotes: 3

Related Questions