Crashalot
Crashalot

Reputation: 34513

Slowly draw quadratic curve on HTML5 canvas

We have an array of points through which we would like to draw a quadratic curve on an HTML5 canvas, but we would like to draw the curve slowly, instead of all at once. Kind of like replaying the drawing of the curve.

Original curve: http://jsfiddle.net/NWBV4/12/

Curve replay: http://jsfiddle.net/NWBV4/15/

In the curve replay, if we change SEGMENT_PER_POINTS to something very large (e.g., 1000), it draws perfectly in one shot.

But as you can tell, with smaller numbers, there are gaps in the replay of the curve.

Any clues on how we can fix this? We're pretty stuck!

Upvotes: 2

Views: 1895

Answers (1)

ninjagecko
ninjagecko

Reputation: 91092

You should add a sleep primitive in your drawing code. However in javascript, rather than with sleep or wait primitives, this is accomplished in an event-directed manner with setInterval or setTimeout. As demonstrated:

var sec = 1000; // milliseconds

var totalDrawingTime = 5*sec;
var numPointsToDraw = [calculate this];
var waitTimePerPoint = totalDrawingTime/numPointsToDraw;

function slowlyDrawCurve(...) {
    var x = ...;

    function drawNextPointAndWait() {
        x += ...;
        if (x < MAX_CANVAS_SIZE) {
            y = f(x);
            point = [x,y];
            dispatch_to_canvas_function(point);
            setTimeout(helper, waitTimePerPoint);
        }
    }
    drawNextPointAndWait();
}

edit

Demonstration here: http://jsfiddle.net/eJVnU/4/

This was actually a little more interesting. Namely, if you are drawing at intervals on order of a few milliseconds (1000 points means 1 millisecond per update!), you need to be careful how you deal with javascript's timers. The javascript events scheduled with setTimeout may not trigger for a few milliseconds or more, making them unreliable! Therefore what I did was figure out when each segment should be completed by. If we were running ahead of schedule by more than a few milliseconds, we did a setTimeout, BUT, if we were otherwise running behind schedule, we directly performed a recursive call to the segment-drawing routine, shortcutting the event-handling system. This also ensures that the drawing is done smoothly to the human eye, as long as the segments are of roughly equal length.

(If you wanted it done even more smoothly, you could calculate the length of the segment drawn, keep the sum total of arclength drawn, and divide that by some fixed constant rate arclength_per_second to figure out how long things should have taken.)

Upvotes: 1

Related Questions