Bob
Bob

Reputation: 6173

draggable drag event throttling

I am trying to make an animation on html5 canvas which is supposed to follow a draggable div when it is moved around, something like that:

draggable_div.draggable({
    drag: function(e, ui) {
        canvasDrawSomethingNearDraggable(ui);
    }
    stop: function(e, ui) {
        canvasDrawSomethingNearDraggable(ui);
    }
});

function canvasDrawRectangleUnderDraggable {
    for (i = 0; i < 10; i++) { // draw overlapping circles in fixed order
        context.beginPath();
        context.arc(x[i], y[i], 10, 0, 2 * Math.PI, false);
        context.fillStyle = c[i];
        context.fill();
        context.stroke();
    }
}

but the animation lags behind when I move the draggable element (the faster I move it the bigger the gap and it closes only when draggable stop event triggers):

enter image description here

Is there a way to solve or lessen this problem? Should I calculate time between drag events and make fewer calls to drawing function this way or is there a better solution?

Upvotes: 5

Views: 4571

Answers (1)

David Sulc
David Sulc

Reputation: 25994

You probably want to debounce your function so the event handler doesn't get called too often (which slows everything down). See Can someone explain the "debounce" function in Javascript for example.

An implementation of debounce is available within the Underscore library (http://underscorejs.org/#debounce). You can just copy that function to use in your code.

Upvotes: 1

Related Questions