-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcontext2d.patch.js
96 lines (88 loc) · 2.75 KB
/
context2d.patch.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
import {path, Path} from "d3-path";
import {names} from './path-operation-names.js';
if (typeof CanvasRenderingContext2D !== 'undefined') {
patchContext2D(CanvasRenderingContext2D, typeof Path2D !== 'undefined' ? Path2D : undefined)
}
export function patchContext2D(CanvasRenderingContext2D, Path2D) {
const {beginPath, fill, stroke} = CanvasRenderingContext2D.prototype
CanvasRenderingContext2D.prototype.beginPath = function () {
beginPath.apply(this, arguments)
if (!this.canvas._roughEnabled) {
return
}
this._path = path();
this._hasChanges = false;
}
function toSvgString(path2d) {
if (path2d instanceof Path) {
return path2d.toString()
} else if (path2d.toSvgString) {
// @napi-rs/canvas
return path2d.toSvgString()
} else {
throw new Error('Path2D not available for roughness.')
}
}
CanvasRenderingContext2D.prototype.stroke = function (path) {
if (Path2D && path instanceof Path2D) {
this._path = path._path ?? path;
}
if (
// if the rough plugin was not enabled, use raw method
!this.canvas._roughEnabled
// if no path passed in and nothing was changed, use raw method. See https://github.com/pingcap/ossinsight-lite/issues/102
|| (!path && !this._hasChanges)
) {
stroke.apply(this, arguments)
return
}
try {
this.canvas._roughEnabled = false;
this.canvas._rough.path(toSvgString(this._path), {
fill: 'none',
stroke: this.strokeStyle,
strokeWidth: this.lineWidth,
})
this.canvas._roughEnabled = true;
} catch (e) {
console.error(e);
stroke.apply(this, arguments)
} finally {
this.canvas._roughEnabled = true;
}
}
CanvasRenderingContext2D.prototype.fill = function (path) {
if (Path2D && path instanceof Path2D) {
this._path = path._path ?? path;
}
if (!this.canvas._roughEnabled || (!path && !this._hasChanges)) {
fill.apply(this, arguments)
return
}
try {
this.canvas._roughEnabled = false;
this.canvas._rough.path(toSvgString(this._path), {
fill: this.fillStyle,
stroke: this.strokeStyle === 'rgba(0, 0, 0, 0)' ? 'none' : this.strokeStyle,
strokeWidth: this.lineWidth,
})
this.canvas._roughEnabled = true;
} catch (e) {
console.error(e);
fill.apply(this, arguments)
} finally {
this.canvas._roughEnabled = true;
}
};
names.forEach(name => {
const origin = CanvasRenderingContext2D.prototype[name];
CanvasRenderingContext2D.prototype[name] = function () {
origin.apply(this, arguments);
if (!this.canvas._roughEnabled) {
return
}
this._path[name](...arguments);
this._hasChanges = true;
}
})
}