5

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?

Bob
  • 5,809
  • 5
  • 36
  • 53
  • it would be easier seeing your canvasDrawSomethingNearDraggable(ui) function, but you probably would get a better result drawing on drag start in a children of your draggable div so your canvas would move along. – Julien Grégoire Jul 11 '15 at 19:17
  • added something very similar for illustration – Bob Jul 11 '15 at 20:13

1 Answers1

1

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.

Community
  • 1
  • 1
David Sulc
  • 25,946
  • 3
  • 52
  • 54
  • 8
    You mean throttle, not debounce. If you debounce it, then a stream of events arriving every x milliseconds will not result in the handler being called until the stream stops. – Gregory Magarshak Jun 07 '17 at 15:00