Skip to content

Instantly share code, notes, and snippets.

@dmikis
Last active August 29, 2015 13:56
Show Gist options
  • Save dmikis/8917286 to your computer and use it in GitHub Desktop.
Save dmikis/8917286 to your computer and use it in GitHub Desktop.
Draw path specified by SVG-like notation
/**
* Draw a path. Format of the path notation is in some way similar to SVG Path.
* Next commands are supported:
*
* * 'M' - move current context point to (x, y) where x and y are following
* numbers. Example:
*
* ['M', 0, 0]
*
* * 'L' - draw a line from current context point to (x, y) where x and y are
* following numbers. Example:
*
* ['L', 100, 100]
*
* * 'C' - draw a cubic Bezier curve from current context point to (x, y). Control
* point for current point is (x1, y1) and for (x, y) - (x2, y2). Format of the
* parameters is [x1, y1, x2, y2, x, y]. Example:
*
* ['C', 100, 0, 0, 100, 100, 100]
*
* * 'Q' - draw a quadratic Bezier curve from current context point to (x, y) with
* control point (cx, cy). Format of the parameters is [cx, cy, x, y]. Example:
*
* ['Q', 100, 0, 100, 100]
*
* * 'A' - draw an arc from current point to (x, y) width radius R, start angle a1 and end
* angle a2. Format of the paramertes is [x, y, R, a1, a2]. Example:
*
* ['A', 100, 100, 100, -0.5 * Math.PI, 0]
*
* @function
* @param {CanvasRenderingContext2D} ctx Context where path will be drawn.
* @param {Array} path Path description.
*/
drawPath: function (ctx, path) {
var currPathPart;
ctx.beginPath();
while ((currPathPart = path.unshift())) {
switch (currPathPart) {
case 'M':
ctx.moveTo(
path.unshift(),
path.unshift()
);
break;
case 'L':
ctx.lineTo(
path.unshift(),
path.unshift()
);
break;
case 'C':
ctx.bezierCurveTo.apply(ctx, path.splice(0, 6));
break;
case 'Q':
ctx.quadraticCurveTo.apply(ctx, path.splice(0, 4));
break;
case 'A':
ctx.arc.apply(ctx, path.splice(0, 4));
break;
case 'Z':
ctx.closePath();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment