1 | import { SVGPathData } from "./SVGPathData";
|
---|
2 | import { SVGCommand } from "./types";
|
---|
3 |
|
---|
4 | // Encode SVG PathData
|
---|
5 | // http://www.w3.org/TR/SVG/paths.html#PathDataBNF
|
---|
6 |
|
---|
7 | // Private consts : Char groups
|
---|
8 | const WSP = " ";
|
---|
9 |
|
---|
10 | export function encodeSVGPath(commands: SVGCommand | SVGCommand[]) {
|
---|
11 | let str = "";
|
---|
12 |
|
---|
13 | if (!Array.isArray(commands)) {
|
---|
14 | commands = [commands];
|
---|
15 | }
|
---|
16 | for (let i = 0; i < commands.length; i++) {
|
---|
17 | const command = commands[i];
|
---|
18 | if (command.type === SVGPathData.CLOSE_PATH) {
|
---|
19 | str += "z";
|
---|
20 | } else if (command.type === SVGPathData.HORIZ_LINE_TO) {
|
---|
21 | str += (command.relative ? "h" : "H") +
|
---|
22 | command.x;
|
---|
23 | } else if (command.type === SVGPathData.VERT_LINE_TO) {
|
---|
24 | str += (command.relative ? "v" : "V") +
|
---|
25 | command.y;
|
---|
26 | } else if (command.type === SVGPathData.MOVE_TO) {
|
---|
27 | str += (command.relative ? "m" : "M") +
|
---|
28 | command.x + WSP + command.y;
|
---|
29 | } else if (command.type === SVGPathData.LINE_TO) {
|
---|
30 | str += (command.relative ? "l" : "L") +
|
---|
31 | command.x + WSP + command.y;
|
---|
32 | } else if (command.type === SVGPathData.CURVE_TO) {
|
---|
33 | str += (command.relative ? "c" : "C") +
|
---|
34 | command.x1 + WSP + command.y1 +
|
---|
35 | WSP + command.x2 + WSP + command.y2 +
|
---|
36 | WSP + command.x + WSP + command.y;
|
---|
37 | } else if (command.type === SVGPathData.SMOOTH_CURVE_TO) {
|
---|
38 | str += (command.relative ? "s" : "S") +
|
---|
39 | command.x2 + WSP + command.y2 +
|
---|
40 | WSP + command.x + WSP + command.y;
|
---|
41 | } else if (command.type === SVGPathData.QUAD_TO) {
|
---|
42 | str += (command.relative ? "q" : "Q") +
|
---|
43 | command.x1 + WSP + command.y1 +
|
---|
44 | WSP + command.x + WSP + command.y;
|
---|
45 | } else if (command.type === SVGPathData.SMOOTH_QUAD_TO) {
|
---|
46 | str += (command.relative ? "t" : "T") +
|
---|
47 | command.x + WSP + command.y;
|
---|
48 | } else if (command.type === SVGPathData.ARC) {
|
---|
49 | str += (command.relative ? "a" : "A") +
|
---|
50 | command.rX + WSP + command.rY +
|
---|
51 | WSP + command.xRot +
|
---|
52 | WSP + (+command.lArcFlag) + WSP + (+command.sweepFlag) +
|
---|
53 | WSP + command.x + WSP + command.y;
|
---|
54 | } else {
|
---|
55 | // Unknown command
|
---|
56 | throw new Error(
|
---|
57 | `Unexpected command type "${ (command as any).type}" at index ${i}.`);
|
---|
58 | }
|
---|
59 | }
|
---|
60 |
|
---|
61 | return str;
|
---|
62 | }
|
---|