generated from aquaticone/esm-starter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pathHelpers.js
106 lines (91 loc) · 2.25 KB
/
pathHelpers.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
// https://codepen.io/shshaw/pen/XbxvNj?editors=1111
export function getColors(img) {
var colors = {},
data = img.data,
len = data.length,
w = img.width,
h = img.height,
x = 0,
y = 0,
i = 0,
color
for (; i < len; i += 4) {
if (data[i + 3] > 0) {
color =
data[i] + "," + data[i + 1] + "," + data[i + 2] + "," + data[i + 3]
colors[color] = colors[color] || []
x = (i / 4) % w
y = Math.floor(i / 4 / w)
colors[color].push([x, y])
}
}
return colors
}
export function colorsToPaths(colors) {
var output = ""
// Loop through each color to build paths
each(colors, function (color, values) {
var orig = color
color = getColor.apply(null, color.split(","))
if (color === false) {
return
}
var paths = []
var curPath
var w = 1
// Loops through each color's pixels to optimize paths
each(values, function () {
if (curPath && this[1] === curPath[1] && this[0] === curPath[0] + w) {
w++
} else {
if (curPath) {
paths.push(makePathData(curPath[0], curPath[1], w))
w = 1
}
curPath = this
}
})
paths.push(makePathData(curPath[0], curPath[1], w)) // Finish last path
output += makePath(color, paths.join(""))
})
return output
}
function each(obj, fn) {
var length = obj.length,
likeArray = length === 0 || (length > 0 && length - 1 in obj),
i = 0
if (likeArray) {
for (; i < length; i++) {
if (fn.call(obj[i], i, obj[i]) === false) {
break
}
}
} else {
for (i in obj) {
if (fn.call(obj[i], i, obj[i]) === false) {
break
}
}
}
}
function componentToHex(c) {
var hex = parseInt(c).toString(16)
return hex.length == 1 ? "0" + hex : hex
}
function getColor(r, g, b, a) {
a = parseInt(a)
if (a === undefined || a === 255) {
return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b)
}
if (a === 0) {
return false
}
return "rgba(" + r + "," + g + "," + b + "," + a / 255 + ")"
}
// Optimized for horizontal lines
function makePathData(x, y, w) {
return "M" + x + " " + y + "h" + w + ""
}
function makePath(color, data) {
return '<path stroke="' + color + '" d="' + data + '" />\n'
}