forked from dy/svg-path-sdf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
80 lines (62 loc) · 1.74 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
73
74
75
76
77
78
79
80
'use strict'
var pathBounds = require('svg-path-bounds')
var parsePath = require('parse-svg-path')
var drawPath = require('draw-svg-path')
var isSvgPath = require('is-svg-path')
var bitmapSdf = require('bitmap-sdf')
var canvas = document.createElement('canvas')
var ctx = canvas.getContext('2d')
module.exports = pathSdf
function pathSdf (path, options) {
if (!isSvgPath(path)) throw Error('Argument should be valid svg path string')
if (!options) options = {}
var w, h
if (options.shape) {
w = options.shape[0]
h = options.shape[1]
}
else {
w = canvas.width = options.w || options.width || 200
h = canvas.height = options.h || options.height || 200
}
var size = Math.min(w, h)
var stroke = options.stroke || 0
var viewbox = options.viewbox || options.viewBox || pathBounds(path)
var scale = [w / (viewbox[2] - viewbox[0]), h / (viewbox[3] - viewbox[1])]
var maxScale = Math.min(scale[0] || 0, scale[1] || 0) / 2
//clear ctx
ctx.fillStyle = 'black'
ctx.fillRect(0, 0, w, h)
ctx.fillStyle = 'white'
if (stroke) {
if (typeof stroke != 'number') stroke = 1
if (stroke > 0) {
ctx.strokeStyle = 'white'
}
else {
ctx.strokeStyle = 'black'
}
ctx.lineWidth = Math.abs(stroke)
}
ctx.translate(w * .5, h * .5)
ctx.scale(maxScale, maxScale)
//if canvas svg paths api is available
if (global.Path2D) {
var path2d = new Path2D(path)
ctx.fill(path2d)
stroke && ctx.stroke(path2d)
}
//fallback to bezier-curves
else {
var segments = parsePath(path)
drawPath(ctx, segments)
ctx.fill()
stroke && ctx.stroke()
}
ctx.setTransform(1, 0, 0, 1, 0, 0);
var data = bitmapSdf(ctx, {
cutoff: options.cutoff != null ? options.cutoff : .5,
radius: options.radius != null ? options.radius : size * .5
})
return data
}