-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpainter.js
82 lines (64 loc) · 2.65 KB
/
painter.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
class SmoothBorderRadiusWorklet {
static get inputProperties() {
return ['--border-radius-aspect', '--border-radius'];
}
// https://github.com/w3c/css-houdini-drafts/issues/219
// static get inputArguments() {
// return ['*']; // precision
// }
static pointCache = {};
static pathCache = {};
static getPointsForRadius(r, aspect, precision) {
const cacheKey = `${r}:${aspect}:${precision}`;
if (!SmoothBorderRadiusWorklet.pointCache[cacheKey]) {
const aspectI = 1 / aspect;
const aspectR = r ** aspect;
const out = Array(Math.floor((r + 1) * 2 * precision));
const step = 1 / precision;
for (let i = 0, y = 0, point = 0; y <= r; y += step, i++) {
point = Math.abs(aspectR - Math.abs(r - i) ** aspect) ** aspectI;
out[i] = ([i, point]); // out.push([i, point]);
out[out.length - 1 - i] = ([r - point, r - i]); // out.push([r - point, r - i]);
}
SmoothBorderRadiusWorklet.pointCache[cacheKey] = out.sort(([a], [b]) => a - b);
}
return SmoothBorderRadiusWorklet.pointCache[cacheKey];
}
paint(ctx, geom, properties, [precision = 0.5]) {
const hw = geom.width / 2;
const hh = geom.height / 2;
const aspect = Math.max(+properties.get('--border-radius-aspect')[0], 0.00000000001);
const radius = Math.min(+properties.get('--border-radius')[0], hw, hh);
// console.debug('request paint with:', hw, hh, radius);
const cacheKey = `${aspect}:${radius}:${hw}:${hh}`;
if (!SmoothBorderRadiusWorklet.pathCache[cacheKey]) {
const dx = hw - radius;
const dy = hh - radius;
const path = new Path2D();
SmoothBorderRadiusWorklet.pathCache[cacheKey] = path;
const offsets = SmoothBorderRadiusWorklet
.getPointsForRadius(radius, aspect, Number(precision));
for (let i = 0; i < offsets.length * 2; i++) {
const ni = i >= offsets.length;
const [d1, d2] = offsets[ni ? i - offsets.length : i];
const x = ni ? hw + dx + d2 : d1;
const y = ni ? hh + hh - d1 : hh + dy + d2;
if (i === 0) path.moveTo(x, y);
else path.lineTo(x, y);
}
path.lineTo(hw + hw, hh - dy);
path.lineTo(0, hh - dy);
for (let i = 0; i < offsets.length * 2; i++) {
const ni = i >= offsets.length;
const [d1, d2] = offsets[ni ? i - offsets.length : i];
const x = ni ? hw + dx + d2 : d1;
const y = ni ? d1 : hh - dy - d2;
if (i === 0) path.moveTo(x, y);
else path.lineTo(x, y);
}
}
ctx.fillStyle = 'black';
ctx.fill(SmoothBorderRadiusWorklet.pathCache[cacheKey]);
}
}
registerPaint('smooth-border-radius', SmoothBorderRadiusWorklet);