Equivalent of canvas quadraticCurveTo in SVG

1.2k views Asked by At

I am working on a plugin to allow "natural looking" signatures to be drawn using mouse or touch. When confirmed by the user, the result will be a stored SVG that can then be displayed in place of the "Click to sign" button.

The attached JSFiddle http://jsfiddle.net/TrueBlueAussie/67haj4nt/3/ shows a testbed for what I am trying to do. The SVG generated image should look close to the original canvas paths.

enter image description here

The first div contains a canvas, in which I draw some multiple-segment lines (e.g. paths). Using quadraticCurveTo, and a midpoint for the control point, I draw the lines with smooth curves. This works just fine.

The key part of the curved line drawing is:

$.each(lines, function () {
    if (this.length > 0) {
        var lastPoint = this[0];
        ctx.moveTo(lastPoint[0], lastPoint[1]);
        for (var i = 1; i < this.length; i++) {
            var point = this[i];
            var midPoint = [(lastPoint[0] + point[0]) / 2, (lastPoint[1] + point[1]) / 2];
            ctx.quadraticCurveTo(lastPoint[0], lastPoint[1], midPoint[0], midPoint[1]);
            lastPoint = point;
        }
        // Draw the last line straight
        ctx.lineTo(lastPoint[0], lastPoint[1]);
    }
});

I have tried multiple options for SVG generation of the same output, but I am stumped on how to convert the same sets of points to equivalent curved lines. Quadratic Beziers require "proper" control points, but I would prefer to use the far simpler mid-points if possible.

Any ideas? Is this possible or will I have to convert both to use Beziers with calculated control point(s). Is there a simple way to calculate control points that will do the same job?

jQuery or raw JavaScript solutions are fine, but you need to demonstrate in the JSFiddle provided :)

1

There are 1 answers

10
Paul LeBeau On BEST ANSWER

It's just a bug in your code. You are not updating lastPoint in your SVG version.

http://jsfiddle.net/67haj4nt/4/

And if you update the SVG version to match the canvas version, you get identical curves.

http://jsfiddle.net/67haj4nt/5/