This repository has been archived by the owner on Jul 24, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathindex.js
72 lines (61 loc) · 2.34 KB
/
index.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
70
71
72
const {CSG} = require('@jscad/csg')
const stringify = require('onml/lib/stringify')
const mimeType = 'image/svg+xml'
const serialize = function (cagObject, options) {
options && options.statusCallback && options.statusCallback({progress: 0})
var decimals = 1000
// mirror the CAG about the X axis in order to generate paths into the POSITIVE direction
var plane = new CSG.Plane(CSG.Vector3D.Create(0, 1, 0), 0)
var cag = cagObject.transform(CSG.Matrix4x4.mirroring(plane))
var bounds = cag.getBounds()
var paths = cag.getOutlinePaths()
var width = Math.round((bounds[1].x - bounds[0].x) * decimals) / decimals
var height = Math.round((bounds[1].y - bounds[0].y) * decimals) / decimals
var body = ['svg',
{
width: width + 'mm',
height: height + 'mm',
viewBox: ('0 0 ' + width + ' ' + height),
version: '1.1',
baseProfile: 'tiny',
xmlns: 'http://www.w3.org/2000/svg',
'xmlns:xlink': 'http://www.w3.org/1999/xlink'
},
PathsToSvg(paths, bounds)
]
var svg = `<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated by OpenJSCAD.org -->
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1 Tiny//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-tiny.dtd">
${stringify(body)}`
options && options.statusCallback && options.statusCallback({progress: 100})
return [svg]
}
const PathsToSvg = function (paths, bounds, options) {
// calculate offsets in order to create paths orientated from the 0,0 axis
var xoffset = 0 - bounds[0].x
var yoffset = 0 - bounds[0].y
return paths.reduce(function (res, path, i) {
options && options.statusCallback && options.statusCallback({progress: 100 * i / paths.length})
return res.concat([['path', {d: dPath(path, xoffset, yoffset)}]])
}, ['g'])
}
const dPath = function (path, xoffset, yoffset) {
var pointindex
var str = ''
var numpointsClosed = path.points.length + (path.closed ? 1 : 0)
for (pointindex = 0; pointindex < numpointsClosed; pointindex++) {
var pointindexwrapped = pointindex
if (pointindexwrapped >= path.points.length) pointindexwrapped -= path.points.length
var point = path.points[pointindexwrapped]
if (pointindex > 0) {
str += `L${(point.x + xoffset)} ${(point.y + yoffset)}`
} else {
str += `M${(point.x + xoffset)} ${(point.y + yoffset)}`
}
}
return str
}
module.exports = {
serialize,
mimeType
}