-
Notifications
You must be signed in to change notification settings - Fork 16
/
SVGLoader.js
69 lines (56 loc) · 2.16 KB
/
SVGLoader.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import {SVGPathData} from '../node_modules/svg-pathdata';
export default class SVGLoader {
constructor() {}
static load(svgString) {
let parser = new DOMParser();
let svgNode = parser.parseFromString(svgString, 'image/svg+xml');
let inputPaths = svgNode.querySelectorAll('path'),
paths = [];
// Scrape all points from all paths, and record breakpoints
for(let inputPath of inputPaths) {
let pathData = new SVGPathData(inputPath.getAttribute('d')),
points = [];
let previousCoords = {
x: 0,
y: 0
};
for(let [index, command] of pathData.commands.entries()) {
switch(command.type) {
// Move ('M') and line ('L') commands have both X and Y
case SVGPathData.MOVE_TO:
case SVGPathData.LINE_TO:
points.push([command.x, command.y]);
break;
// Horizontal line ('H') commands only have X, using previous command's Y
case SVGPathData.HORIZ_LINE_TO:
points.push([command.x, previousCoords.y]);
break;
// Vertical line ('V') commands only have Y, using previous command's X
case SVGPathData.VERT_LINE_TO:
points.push([previousCoords.x, command.y]);
break;
// ClosePath ('Z') commands are a naive indication that the current path can be processed and added to the world
case SVGPathData.CLOSE_PATH:
// Capture path in return object
paths.push(points);
points = [];
break;
}
// Unclosed paths never have CLOSE_PATH commands, so wrap up the current path when we're at the end of the path and have not found the command
if(index == pathData.commands.length - 1 && command.type != SVGPathData.CLOSE_PATH) {
paths.push(points);
points = [];
}
// Capture X coordinate, if there was one
if(command.hasOwnProperty('x')) {
previousCoords.x = command.x;
}
// Capture Y coordinate, if there was one
if(command.hasOwnProperty('y')) {
previousCoords.y = command.y;
}
}
}
return paths;
}
}