@antv/g-canvas 2.0.52 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +3 -3
  2. package/dist/index.esm.js +2580 -20
  3. package/dist/index.esm.js.map +1 -1
  4. package/dist/index.js +2588 -38
  5. package/dist/index.js.map +1 -1
  6. package/dist/index.umd.min.js +7 -31
  7. package/dist/index.umd.min.js.map +1 -1
  8. package/package.json +7 -11
  9. package/types/index.d.ts +7 -8
  10. package/types/index.d.ts.map +1 -1
  11. package/types/plugins/canvas-renderer/CanvasRendererPlugin.d.ts +49 -0
  12. package/types/plugins/canvas-renderer/CanvasRendererPlugin.d.ts.map +1 -0
  13. package/types/plugins/canvas-renderer/index.d.ts +17 -0
  14. package/types/plugins/canvas-renderer/index.d.ts.map +1 -0
  15. package/types/plugins/canvas-renderer/interfaces.d.ts +5 -0
  16. package/types/plugins/canvas-renderer/interfaces.d.ts.map +1 -0
  17. package/types/plugins/canvas-renderer/shapes/styles/Default.d.ts +14 -0
  18. package/types/plugins/canvas-renderer/shapes/styles/Default.d.ts.map +1 -0
  19. package/types/plugins/canvas-renderer/shapes/styles/Image.d.ts +19 -0
  20. package/types/plugins/canvas-renderer/shapes/styles/Image.d.ts.map +1 -0
  21. package/types/plugins/canvas-renderer/shapes/styles/OptimizedDefault.d.ts +37 -0
  22. package/types/plugins/canvas-renderer/shapes/styles/OptimizedDefault.d.ts.map +1 -0
  23. package/types/plugins/canvas-renderer/shapes/styles/Text.d.ts +19 -0
  24. package/types/plugins/canvas-renderer/shapes/styles/Text.d.ts.map +1 -0
  25. package/types/plugins/canvas-renderer/shapes/styles/helper.d.ts +5 -0
  26. package/types/plugins/canvas-renderer/shapes/styles/helper.d.ts.map +1 -0
  27. package/types/plugins/canvas-renderer/shapes/styles/index.d.ts +13 -0
  28. package/types/plugins/canvas-renderer/shapes/styles/index.d.ts.map +1 -0
  29. package/types/plugins/canvas-renderer/shapes/styles/interfaces.d.ts +8 -0
  30. package/types/plugins/canvas-renderer/shapes/styles/interfaces.d.ts.map +1 -0
  31. package/types/plugins/canvas-renderer/utils/math.d.ts +8 -0
  32. package/types/plugins/canvas-renderer/utils/math.d.ts.map +1 -0
  33. package/types/plugins/path-generator/index.d.ts +11 -0
  34. package/types/plugins/path-generator/index.d.ts.map +1 -0
  35. package/types/plugins/path-generator/interfaces.d.ts +6 -0
  36. package/types/plugins/path-generator/interfaces.d.ts.map +1 -0
  37. package/types/plugins/path-generator/paths/Circle.d.ts +3 -0
  38. package/types/plugins/path-generator/paths/Circle.d.ts.map +1 -0
  39. package/types/plugins/path-generator/paths/Ellipse.d.ts +3 -0
  40. package/types/plugins/path-generator/paths/Ellipse.d.ts.map +1 -0
  41. package/types/plugins/path-generator/paths/Line.d.ts +3 -0
  42. package/types/plugins/path-generator/paths/Line.d.ts.map +1 -0
  43. package/types/plugins/path-generator/paths/Path.d.ts +3 -0
  44. package/types/plugins/path-generator/paths/Path.d.ts.map +1 -0
  45. package/types/plugins/path-generator/paths/Polygon.d.ts +3 -0
  46. package/types/plugins/path-generator/paths/Polygon.d.ts.map +1 -0
  47. package/types/plugins/path-generator/paths/Polyline.d.ts +3 -0
  48. package/types/plugins/path-generator/paths/Polyline.d.ts.map +1 -0
  49. package/types/plugins/path-generator/paths/Rect.d.ts +3 -0
  50. package/types/plugins/path-generator/paths/Rect.d.ts.map +1 -0
  51. package/types/plugins/path-generator/paths/index.d.ts +8 -0
  52. package/types/plugins/path-generator/paths/index.d.ts.map +1 -0
  53. package/types/plugins/picker/CanvasPickerPlugin.d.ts +23 -0
  54. package/types/plugins/picker/CanvasPickerPlugin.d.ts.map +1 -0
  55. package/types/plugins/picker/Circle.d.ts +3 -0
  56. package/types/plugins/picker/Circle.d.ts.map +1 -0
  57. package/types/plugins/picker/Ellipse.d.ts +3 -0
  58. package/types/plugins/picker/Ellipse.d.ts.map +1 -0
  59. package/types/plugins/picker/Image.d.ts +3 -0
  60. package/types/plugins/picker/Image.d.ts.map +1 -0
  61. package/types/plugins/picker/Line.d.ts +3 -0
  62. package/types/plugins/picker/Line.d.ts.map +1 -0
  63. package/types/plugins/picker/Path.d.ts +3 -0
  64. package/types/plugins/picker/Path.d.ts.map +1 -0
  65. package/types/plugins/picker/Polygon.d.ts +3 -0
  66. package/types/plugins/picker/Polygon.d.ts.map +1 -0
  67. package/types/plugins/picker/Polyline.d.ts +3 -0
  68. package/types/plugins/picker/Polyline.d.ts.map +1 -0
  69. package/types/plugins/picker/Rect.d.ts +4 -0
  70. package/types/plugins/picker/Rect.d.ts.map +1 -0
  71. package/types/plugins/picker/Text.d.ts +3 -0
  72. package/types/plugins/picker/Text.d.ts.map +1 -0
  73. package/types/plugins/picker/index.d.ts +7 -0
  74. package/types/plugins/picker/index.d.ts.map +1 -0
  75. package/types/plugins/picker/utils/math.d.ts +8 -0
  76. package/types/plugins/picker/utils/math.d.ts.map +1 -0
package/dist/index.esm.js CHANGED
@@ -1,8 +1,8 @@
1
1
  /*!
2
2
  * @antv/g-canvas
3
3
  * @description A renderer implemented by Canvas 2D API
4
- * @version 2.0.52
5
- * @date 12/12/2025, 3:32:34 AM
4
+ * @version 2.2.0
5
+ * @date 12/24/2025, 11:55:53 AM
6
6
  * @author AntVis
7
7
  * @docs https://g.antv.antgroup.com/
8
8
  */
@@ -10,22 +10,2582 @@ import _createClass from '@babel/runtime/helpers/createClass';
10
10
  import _classCallCheck from '@babel/runtime/helpers/classCallCheck';
11
11
  import _callSuper from '@babel/runtime/helpers/callSuper';
12
12
  import _inherits from '@babel/runtime/helpers/inherits';
13
- import { setDOMSize, RenderReason, AbstractRendererPlugin, AbstractRenderer } from '@antv/g-lite';
14
- import * as CanvasPathGenerator from '@antv/g-plugin-canvas-path-generator';
15
- export { CanvasPathGenerator };
16
- import * as CanvasPicker from '@antv/g-plugin-canvas-picker';
17
- export { CanvasPicker };
18
- import * as CanvasRenderer from '@antv/g-plugin-canvas-renderer';
19
- export { CanvasRenderer };
20
- import * as DomInteraction from '@antv/g-plugin-dom-interaction';
21
- export { DomInteraction };
22
- import * as HTMLRenderer from '@antv/g-plugin-html-renderer';
23
- export { HTMLRenderer };
24
- import * as ImageLoader from '@antv/g-plugin-image-loader';
25
- export { ImageLoader };
13
+ import { AABB, CustomEvent, CanvasEvent, Shape, Node, GradientType, isPattern, AbstractRendererPlugin, findClosestClipPathTarget, Point, isFillOrStrokeAffected, getOrCalculatePathTotalLength, isDisplayObject, setDOMSize, RenderReason, AbstractRenderer, ImageLoader, DomInteraction, HTMLRenderer } from '@antv/g-lite';
14
+ export { DomInteraction, HTMLRenderer, ImageLoader } from '@antv/g-lite';
15
+ import _defineProperty from '@babel/runtime/helpers/defineProperty';
16
+ import _objectSpread from '@babel/runtime/helpers/objectSpread2';
17
+ import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
18
+ import _classPrivateFieldLooseBase from '@babel/runtime/helpers/classPrivateFieldLooseBase';
19
+ import _classPrivateFieldLooseKey from '@babel/runtime/helpers/classPrivateFieldLooseKey';
20
+ import { mat4, vec3 } from 'gl-matrix';
21
+ import { isNil, arcToCubic, clamp, isString } from '@antv/util';
22
+ import _createForOfIteratorHelper from '@babel/runtime/helpers/createForOfIteratorHelper';
26
23
  import _regeneratorRuntime from '@babel/runtime/helpers/regeneratorRuntime';
27
24
  import _asyncToGenerator from '@babel/runtime/helpers/asyncToGenerator';
28
- import { isString } from '@antv/util';
25
+ import { distance, linePointToLine, cubicPointDistance, quadPointDistance } from '@antv/g-math';
26
+
27
+ var _renderState = /*#__PURE__*/_classPrivateFieldLooseKey("renderState");
28
+ /**
29
+ * support 2 modes in rendering:
30
+ * * immediate
31
+ * * delayed: render at the end of frame with dirty-rectangle
32
+ */
33
+ var CanvasRendererPlugin = /*#__PURE__*/function () {
34
+ function CanvasRendererPlugin(canvasRendererPluginOptions // private styleRendererFactory: Record<Shape, StyleRenderer>,
35
+ ) {
36
+ _classCallCheck(this, CanvasRendererPlugin);
37
+ this.renderQueue = [];
38
+ Object.defineProperty(this, _renderState, {
39
+ writable: true,
40
+ value: {
41
+ restoreStack: [],
42
+ prevObject: null,
43
+ currentContext: new Map()
44
+ }
45
+ });
46
+ this.clearFullScreenLastFrame = false;
47
+ this.clearFullScreen = false;
48
+ /**
49
+ * view projection matrix
50
+ */
51
+ this.vpMatrix = mat4.create();
52
+ this.dprMatrix = mat4.create();
53
+ this.tmpMat4 = mat4.create();
54
+ this.vec3a = vec3.create();
55
+ this.vec3b = vec3.create();
56
+ this.vec3c = vec3.create();
57
+ this.vec3d = vec3.create();
58
+ this.canvasRendererPluginOptions = canvasRendererPluginOptions;
59
+ }
60
+ return _createClass(CanvasRendererPlugin, [{
61
+ key: "apply",
62
+ value: function apply(context, runtime) {
63
+ var _this = this;
64
+ this.context = context;
65
+ var _this$context = this.context,
66
+ config = _this$context.config,
67
+ camera = _this$context.camera,
68
+ renderingService = _this$context.renderingService,
69
+ renderingContext = _this$context.renderingContext,
70
+ pathGeneratorFactory = _this$context.pathGeneratorFactory;
71
+ var enableRenderingOptimization = config.renderer.getConfig().enableRenderingOptimization;
72
+ config.renderer.getConfig().enableDirtyCheck = false;
73
+ config.renderer.getConfig().enableDirtyRectangleRendering = false;
74
+ this.pathGeneratorFactory = pathGeneratorFactory;
75
+ var contextService = context.contextService;
76
+ var canvas = renderingContext.root.ownerDocument.defaultView;
77
+ renderingService.hooks.init.tap(CanvasRendererPlugin.tag, function () {
78
+ // clear fullscreen
79
+ var dpr = contextService.getDPR();
80
+ var width = config.width,
81
+ height = config.height;
82
+ var context = contextService.getContext();
83
+ _this.clearRect(context, 0, 0, width * dpr, height * dpr, config.background);
84
+ });
85
+ renderingService.hooks.destroy.tap(CanvasRendererPlugin.tag, function () {
86
+ _this.renderQueue = [];
87
+ _classPrivateFieldLooseBase(_this, _renderState)[_renderState] = {
88
+ restoreStack: [],
89
+ prevObject: null,
90
+ currentContext: null
91
+ };
92
+ });
93
+ var beforeDraw = function beforeDraw() {
94
+ var _canvas$context$rende;
95
+ var context = contextService.getContext();
96
+ var dpr = contextService.getDPR();
97
+ var width = config.width,
98
+ height = config.height;
99
+ var _this$canvasRendererP = _this.canvasRendererPluginOptions,
100
+ dirtyObjectNumThreshold = _this$canvasRendererP.dirtyObjectNumThreshold,
101
+ dirtyObjectRatioThreshold = _this$canvasRendererP.dirtyObjectRatioThreshold;
102
+
103
+ // some heuristic conditions such as 80% object changed
104
+ var _renderingService$get = renderingService.getStats(),
105
+ total = _renderingService$get.total,
106
+ rendered = _renderingService$get.rendered;
107
+ var ratio = rendered / total;
108
+ _this.clearFullScreen = _this.clearFullScreenLastFrame ||
109
+ // @ts-ignore
110
+ !((_canvas$context$rende = canvas.context.renderingPlugins[1]) !== null && _canvas$context$rende !== void 0 && _canvas$context$rende.isFirstTimeRenderingFinished) || renderingService.disableDirtyRectangleRendering() || rendered > dirtyObjectNumThreshold && ratio > dirtyObjectRatioThreshold;
111
+ if (!context) {
112
+ return;
113
+ }
114
+ if (typeof context.resetTransform === 'function') {
115
+ context.resetTransform();
116
+ } else {
117
+ context.setTransform(1, 0, 0, 1, 0, 0);
118
+ }
119
+ if (_this.clearFullScreen) {
120
+ _this.clearRect(context, 0, 0, width * dpr, height * dpr, config.background);
121
+ }
122
+ };
123
+
124
+ /**
125
+ * render objects by z-index
126
+ *
127
+ * - The level of the child node will be affected by the level of the parent node
128
+ */
129
+ var renderByZIndex = function renderByZIndex(object, context) {
130
+ var stack = [object];
131
+ while (stack.length > 0) {
132
+ var _currentObject$sortab;
133
+ var currentObject = stack.pop();
134
+ if (currentObject.isVisible() && !currentObject.isCulled()) {
135
+ if (enableRenderingOptimization) {
136
+ _this.renderDisplayObjectOptimized(currentObject, context, _this.context, _classPrivateFieldLooseBase(_this, _renderState)[_renderState], runtime);
137
+ } else {
138
+ _this.renderDisplayObject(currentObject, context, _this.context, _classPrivateFieldLooseBase(_this, _renderState)[_renderState], runtime);
139
+ }
140
+ }
141
+ var objects = ((_currentObject$sortab = currentObject.sortable) === null || _currentObject$sortab === void 0 || (_currentObject$sortab = _currentObject$sortab.sorted) === null || _currentObject$sortab === void 0 ? void 0 : _currentObject$sortab.length) > 0 ? currentObject.sortable.sorted : currentObject.childNodes;
142
+ // should account for z-index
143
+ for (var i = objects.length - 1; i >= 0; i--) {
144
+ stack.push(objects[i]);
145
+ }
146
+ }
147
+ };
148
+
149
+ // render at the end of frame
150
+ renderingService.hooks.endFrame.tap(CanvasRendererPlugin.tag, function () {
151
+ beforeDraw();
152
+
153
+ // Skip rendering.
154
+ if (renderingContext.root.childNodes.length === 0) {
155
+ _this.clearFullScreenLastFrame = true;
156
+ return;
157
+ }
158
+ enableRenderingOptimization = config.renderer.getConfig().enableRenderingOptimization;
159
+
160
+ // init
161
+ _classPrivateFieldLooseBase(_this, _renderState)[_renderState] = {
162
+ restoreStack: [],
163
+ prevObject: null,
164
+ currentContext: _classPrivateFieldLooseBase(_this, _renderState)[_renderState].currentContext
165
+ };
166
+ _classPrivateFieldLooseBase(_this, _renderState)[_renderState].currentContext.clear();
167
+ _this.clearFullScreenLastFrame = false;
168
+ var context = contextService.getContext();
169
+ // clear & clip dirty rectangle
170
+ var dpr = contextService.getDPR();
171
+ mat4.fromScaling(_this.dprMatrix, [dpr, dpr, 1]);
172
+ mat4.multiply(_this.vpMatrix, _this.dprMatrix, camera.getOrthoMatrix());
173
+ if (_this.clearFullScreen) {
174
+ // console.time('renderByZIndex');
175
+ if (enableRenderingOptimization) {
176
+ context.save();
177
+ renderByZIndex(renderingContext.root, context);
178
+ context.restore();
179
+ } else {
180
+ renderByZIndex(renderingContext.root, context);
181
+ }
182
+ // console.timeEnd('renderByZIndex');
183
+ } else {
184
+ // console.log('canvas renderer next...', this.renderQueue);
185
+ // merge removed AABB
186
+ var dirtyRenderBounds = _this.safeMergeAABB(_this.mergeDirtyAABBs(_this.renderQueue));
187
+ if (AABB.isEmpty(dirtyRenderBounds)) {
188
+ _this.renderQueue = [];
189
+ return;
190
+ }
191
+ var dirtyRect = _this.convertAABB2Rect(dirtyRenderBounds);
192
+ var x = dirtyRect.x,
193
+ y = dirtyRect.y,
194
+ width = dirtyRect.width,
195
+ height = dirtyRect.height;
196
+ var tl = vec3.transformMat4(_this.vec3a, [x, y, 0], _this.vpMatrix);
197
+ var tr = vec3.transformMat4(_this.vec3b, [x + width, y, 0], _this.vpMatrix);
198
+ var bl = vec3.transformMat4(_this.vec3c, [x, y + height, 0], _this.vpMatrix);
199
+ var br = vec3.transformMat4(_this.vec3d, [x + width, y + height, 0], _this.vpMatrix);
200
+ var minx = Math.min(tl[0], tr[0], br[0], bl[0]);
201
+ var miny = Math.min(tl[1], tr[1], br[1], bl[1]);
202
+ var maxx = Math.max(tl[0], tr[0], br[0], bl[0]);
203
+ var maxy = Math.max(tl[1], tr[1], br[1], bl[1]);
204
+ var ix = Math.floor(minx);
205
+ var iy = Math.floor(miny);
206
+ var iwidth = Math.ceil(maxx - minx);
207
+ var iheight = Math.ceil(maxy - miny);
208
+ context.save();
209
+ _this.clearRect(context, ix, iy, iwidth, iheight, config.background);
210
+ context.beginPath();
211
+ context.rect(ix, iy, iwidth, iheight);
212
+ context.clip();
213
+
214
+ // @see https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Transformations
215
+ context.setTransform(_this.vpMatrix[0], _this.vpMatrix[1], _this.vpMatrix[4], _this.vpMatrix[5], _this.vpMatrix[12], _this.vpMatrix[13]);
216
+
217
+ // draw dirty rectangle
218
+ var _config$renderer$getC = config.renderer.getConfig(),
219
+ enableDirtyRectangleRenderingDebug = _config$renderer$getC.enableDirtyRectangleRenderingDebug;
220
+ if (enableDirtyRectangleRenderingDebug) {
221
+ canvas.dispatchEvent(new CustomEvent(CanvasEvent.DIRTY_RECTANGLE, {
222
+ dirtyRect: {
223
+ x: ix,
224
+ y: iy,
225
+ width: iwidth,
226
+ height: iheight
227
+ }
228
+ }));
229
+ }
230
+
231
+ // search objects intersect with dirty rectangle
232
+ var _dirtyRenderBounds$ge = dirtyRenderBounds.getMin(),
233
+ _dirtyRenderBounds$ge2 = _slicedToArray(_dirtyRenderBounds$ge, 2),
234
+ minX = _dirtyRenderBounds$ge2[0],
235
+ minY = _dirtyRenderBounds$ge2[1];
236
+ var _dirtyRenderBounds$ge3 = dirtyRenderBounds.getMax(),
237
+ _dirtyRenderBounds$ge4 = _slicedToArray(_dirtyRenderBounds$ge3, 2),
238
+ maxX = _dirtyRenderBounds$ge4[0],
239
+ maxY = _dirtyRenderBounds$ge4[1];
240
+ var dirtyObjects = renderingContext.root.ownerDocument.elementsFromBBox(minX, minY, maxX, maxY);
241
+
242
+ // do rendering
243
+ dirtyObjects
244
+ // sort by z-index
245
+ .sort(function (a, b) {
246
+ return a.sortable.renderOrder - b.sortable.renderOrder;
247
+ }).forEach(function (object) {
248
+ // culled object should not be rendered
249
+ if (object && object.isVisible() && !object.isCulled()) {
250
+ _this.renderDisplayObject(object, context, _this.context, _classPrivateFieldLooseBase(_this, _renderState)[_renderState], runtime);
251
+ }
252
+ });
253
+ context.restore();
254
+
255
+ // save dirty AABBs in last frame
256
+ _this.renderQueue.forEach(function (object) {
257
+ _this.saveDirtyAABB(object);
258
+ });
259
+
260
+ // clear queue
261
+ _this.renderQueue = [];
262
+ }
263
+
264
+ // pop restore stack, eg. root -> parent -> child
265
+ _classPrivateFieldLooseBase(_this, _renderState)[_renderState].restoreStack.forEach(function () {
266
+ context.restore();
267
+ });
268
+ // clear restore stack
269
+ _classPrivateFieldLooseBase(_this, _renderState)[_renderState].restoreStack = [];
270
+ });
271
+ renderingService.hooks.render.tap(CanvasRendererPlugin.tag, function (object) {
272
+ if (!_this.clearFullScreen) {
273
+ // render at the end of frame
274
+ _this.renderQueue.push(object);
275
+ }
276
+ });
277
+ }
278
+ }, {
279
+ key: "clearRect",
280
+ value: function clearRect(context, x, y, width, height, background) {
281
+ // clearRect is faster than fillRect @see https://stackoverflow.com/a/30830253
282
+ context.clearRect(x, y, width, height);
283
+ if (background) {
284
+ context.fillStyle = background;
285
+ context.fillRect(x, y, width, height);
286
+ }
287
+ }
288
+ }, {
289
+ key: "renderDisplayObjectOptimized",
290
+ value: function renderDisplayObjectOptimized(object, context, canvasContext, renderState, runtime) {
291
+ var nodeName = object.nodeName;
292
+ var updateTransform = false;
293
+ var clipDraw = false;
294
+
295
+ // @ts-ignore
296
+ var styleRenderer = this.context.styleRendererFactory[nodeName];
297
+ var generatePath = this.pathGeneratorFactory[nodeName];
298
+
299
+ // clip path
300
+ var clipPath = object.parsedStyle.clipPath;
301
+ if (clipPath) {
302
+ updateTransform = !renderState.prevObject || !mat4.exactEquals(clipPath.getWorldTransform(), renderState.prevObject.getWorldTransform());
303
+ if (updateTransform) {
304
+ this.applyWorldTransform(context, clipPath);
305
+ renderState.prevObject = null;
306
+ }
307
+
308
+ // generate path in local space
309
+ var _generatePath = this.pathGeneratorFactory[clipPath.nodeName];
310
+ if (_generatePath) {
311
+ context.save();
312
+ clipDraw = true;
313
+ context.beginPath();
314
+ _generatePath(context, clipPath.parsedStyle);
315
+ context.closePath();
316
+ context.clip();
317
+ }
318
+ }
319
+
320
+ // fill & stroke
321
+
322
+ if (styleRenderer) {
323
+ updateTransform = !renderState.prevObject || !mat4.exactEquals(object.getWorldTransform(), renderState.prevObject.getWorldTransform());
324
+ if (updateTransform) {
325
+ this.applyWorldTransform(context, object);
326
+ }
327
+ var forceUpdateStyle = !renderState.prevObject;
328
+ if (!forceUpdateStyle) {
329
+ var prevNodeName = renderState.prevObject.nodeName;
330
+ if (nodeName === Shape.TEXT) {
331
+ forceUpdateStyle = prevNodeName !== Shape.TEXT;
332
+ } else if (nodeName === Shape.IMAGE) {
333
+ forceUpdateStyle = prevNodeName !== Shape.IMAGE;
334
+ } else {
335
+ forceUpdateStyle = prevNodeName === Shape.TEXT || prevNodeName === Shape.IMAGE;
336
+ }
337
+ }
338
+ styleRenderer.applyStyleToContext(context, object, forceUpdateStyle, renderState);
339
+ renderState.prevObject = object;
340
+ }
341
+ if (generatePath) {
342
+ context.beginPath();
343
+ generatePath(context, object.parsedStyle);
344
+ if (nodeName !== Shape.LINE && nodeName !== Shape.PATH && nodeName !== Shape.POLYLINE) {
345
+ context.closePath();
346
+ }
347
+ }
348
+
349
+ // fill & stroke
350
+ if (styleRenderer) {
351
+ styleRenderer.drawToContext(context, object, _classPrivateFieldLooseBase(this, _renderState)[_renderState], this, runtime);
352
+ }
353
+ if (clipDraw) {
354
+ context.restore();
355
+ }
356
+
357
+ // finish rendering, clear dirty flag
358
+ object.dirty(false);
359
+ }
360
+ }, {
361
+ key: "renderDisplayObject",
362
+ value: function renderDisplayObject(object, context, canvasContext, renderState, runtime) {
363
+ var nodeName = object.nodeName;
364
+
365
+ // restore to its ancestor
366
+
367
+ var parent = renderState.restoreStack[renderState.restoreStack.length - 1];
368
+ if (parent && !(object.compareDocumentPosition(parent) & Node.DOCUMENT_POSITION_CONTAINS)) {
369
+ context.restore();
370
+ renderState.restoreStack.pop();
371
+ }
372
+
373
+ // @ts-ignore
374
+ var styleRenderer = this.context.styleRendererFactory[nodeName];
375
+ var generatePath = this.pathGeneratorFactory[nodeName];
376
+
377
+ // clip path
378
+ var clipPath = object.parsedStyle.clipPath;
379
+ if (clipPath) {
380
+ this.applyWorldTransform(context, clipPath);
381
+
382
+ // generate path in local space
383
+ var _generatePath2 = this.pathGeneratorFactory[clipPath.nodeName];
384
+ if (_generatePath2) {
385
+ context.save();
386
+
387
+ // save clip
388
+ renderState.restoreStack.push(object);
389
+ context.beginPath();
390
+ _generatePath2(context, clipPath.parsedStyle);
391
+ context.closePath();
392
+ context.clip();
393
+ }
394
+ }
395
+
396
+ // fill & stroke
397
+
398
+ if (styleRenderer) {
399
+ this.applyWorldTransform(context, object);
400
+ context.save();
401
+
402
+ // apply attributes to context
403
+ this.applyAttributesToContext(context, object);
404
+ }
405
+ if (generatePath) {
406
+ context.beginPath();
407
+ generatePath(context, object.parsedStyle);
408
+ if (nodeName !== Shape.LINE && nodeName !== Shape.PATH && nodeName !== Shape.POLYLINE) {
409
+ context.closePath();
410
+ }
411
+ }
412
+
413
+ // fill & stroke
414
+ if (styleRenderer) {
415
+ styleRenderer.render(context, object.parsedStyle, object, canvasContext, this, runtime);
416
+
417
+ // restore applied attributes, eg. shadowBlur shadowColor...
418
+ context.restore();
419
+ }
420
+
421
+ // finish rendering, clear dirty flag
422
+ object.dirty(false);
423
+ }
424
+ }, {
425
+ key: "applyAttributesToContext",
426
+ value: function applyAttributesToContext(context, object) {
427
+ var _ref = object.parsedStyle,
428
+ stroke = _ref.stroke,
429
+ fill = _ref.fill,
430
+ opacity = _ref.opacity,
431
+ lineDash = _ref.lineDash,
432
+ lineDashOffset = _ref.lineDashOffset;
433
+ // @see https://developer.mozilla.org/zh-CN/docs/Web/API/CanvasRenderingContext2D/setLineDash
434
+ if (lineDash) {
435
+ context.setLineDash(lineDash);
436
+ }
437
+
438
+ // @see https://developer.mozilla.org/zh-CN/docs/Web/API/CanvasRenderingContext2D/lineDashOffset
439
+ if (!isNil(lineDashOffset)) {
440
+ context.lineDashOffset = lineDashOffset;
441
+ }
442
+ if (!isNil(opacity)) {
443
+ context.globalAlpha *= opacity;
444
+ }
445
+ if (!isNil(stroke) && !Array.isArray(stroke) && !stroke.isNone) {
446
+ context.strokeStyle = object.attributes.stroke;
447
+ }
448
+ if (!isNil(fill) && !Array.isArray(fill) && !fill.isNone) {
449
+ context.fillStyle = object.attributes.fill;
450
+ }
451
+ }
452
+ }, {
453
+ key: "convertAABB2Rect",
454
+ value: function convertAABB2Rect(aabb) {
455
+ var min = aabb.getMin();
456
+ var max = aabb.getMax();
457
+ // expand the rectangle a bit to avoid artifacts
458
+ // @see https://www.yuque.com/antv/ou292n/bi8nix#ExvCu
459
+ var minX = Math.floor(min[0]);
460
+ var minY = Math.floor(min[1]);
461
+ var maxX = Math.ceil(max[0]);
462
+ var maxY = Math.ceil(max[1]);
463
+ var width = maxX - minX;
464
+ var height = maxY - minY;
465
+ return {
466
+ x: minX,
467
+ y: minY,
468
+ width: width,
469
+ height: height
470
+ };
471
+ }
472
+
473
+ /**
474
+ * TODO: merge dirty rectangles with some strategies.
475
+ * For now, we just simply merge all the rectangles into one.
476
+ * @see https://idom.me/articles/841.html
477
+ */
478
+ }, {
479
+ key: "mergeDirtyAABBs",
480
+ value: function mergeDirtyAABBs(dirtyObjects) {
481
+ // merge into a big AABB
482
+ // TODO: skip descendant if ancestor is caculated, but compareNodePosition is really slow
483
+ var aabb = new AABB();
484
+ dirtyObjects.forEach(function (object) {
485
+ var renderBounds = object.getRenderBounds();
486
+ aabb.add(renderBounds);
487
+ var dirtyRenderBounds = object.renderable.dirtyRenderBounds;
488
+ if (dirtyRenderBounds) {
489
+ aabb.add(dirtyRenderBounds);
490
+ }
491
+ });
492
+ return aabb;
493
+ }
494
+ }, {
495
+ key: "saveDirtyAABB",
496
+ value: function saveDirtyAABB(object) {
497
+ var renderable = object.renderable;
498
+ if (!renderable.dirtyRenderBounds) {
499
+ renderable.dirtyRenderBounds = new AABB();
500
+ }
501
+ var renderBounds = object.getRenderBounds();
502
+ if (renderBounds) {
503
+ // save last dirty aabb
504
+ renderable.dirtyRenderBounds.update(renderBounds.center, renderBounds.halfExtents);
505
+ }
506
+ }
507
+ }, {
508
+ key: "applyWorldTransform",
509
+ value: function applyWorldTransform(context, object, matrix) {
510
+ // apply clip shape's RTS
511
+ if (matrix) {
512
+ mat4.copy(this.tmpMat4, object.getLocalTransform());
513
+ mat4.multiply(this.tmpMat4, matrix, this.tmpMat4);
514
+ mat4.multiply(this.tmpMat4, this.vpMatrix, this.tmpMat4);
515
+ } else {
516
+ // apply RTS transformation in world space
517
+ mat4.copy(this.tmpMat4, object.getWorldTransform());
518
+ mat4.multiply(this.tmpMat4, this.vpMatrix, this.tmpMat4);
519
+ }
520
+
521
+ // @see https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Transformations
522
+ context.setTransform(this.tmpMat4[0], this.tmpMat4[1], this.tmpMat4[4], this.tmpMat4[5], this.tmpMat4[12], this.tmpMat4[13]);
523
+ }
524
+ }, {
525
+ key: "safeMergeAABB",
526
+ value: function safeMergeAABB() {
527
+ var merged = new AABB();
528
+ for (var _len = arguments.length, aabbs = new Array(_len), _key = 0; _key < _len; _key++) {
529
+ aabbs[_key] = arguments[_key];
530
+ }
531
+ aabbs.forEach(function (aabb) {
532
+ merged.add(aabb);
533
+ });
534
+ return merged;
535
+ }
536
+ }]);
537
+ }();
538
+ CanvasRendererPlugin.tag = 'CanvasRenderer';
539
+
540
+ function getPattern(pattern, object, context, canvasContext, plugin, runtime, imagePool) {
541
+ var $offscreenCanvas;
542
+ var dpr;
543
+ if (pattern.image.nodeName === 'rect') {
544
+ var _parsedStyle = pattern.image.parsedStyle,
545
+ width = _parsedStyle.width,
546
+ height = _parsedStyle.height;
547
+ dpr = canvasContext.contextService.getDPR();
548
+ var offscreenCanvas = canvasContext.config.offscreenCanvas;
549
+ $offscreenCanvas = runtime.offscreenCanvasCreator.getOrCreateCanvas(offscreenCanvas);
550
+ $offscreenCanvas.width = width * dpr;
551
+ $offscreenCanvas.height = height * dpr;
552
+ var offscreenCanvasContext = runtime.offscreenCanvasCreator.getOrCreateContext(offscreenCanvas);
553
+ var renderState = {
554
+ restoreStack: [],
555
+ prevObject: null,
556
+ currentContext: new Map()
557
+ };
558
+
559
+ // offscreenCanvasContext.scale(1 / dpr, 1 / dpr);
560
+
561
+ pattern.image.forEach(function (object) {
562
+ plugin.renderDisplayObject(object, offscreenCanvasContext, canvasContext, renderState, runtime);
563
+ });
564
+ renderState.restoreStack.forEach(function () {
565
+ offscreenCanvasContext.restore();
566
+ });
567
+ }
568
+ var canvasPattern = imagePool.getOrCreatePatternSync(object, pattern, context, $offscreenCanvas, dpr, object.getGeometryBounds().min, function () {
569
+ // set dirty rectangle flag
570
+ object.dirty();
571
+ canvasContext.renderingService.dirty();
572
+ });
573
+ return canvasPattern;
574
+ }
575
+ function getColor(parsedColor, object, context, imagePool) {
576
+ var color;
577
+ if (parsedColor.type === GradientType.LinearGradient || parsedColor.type === GradientType.RadialGradient) {
578
+ var bounds = object.getGeometryBounds();
579
+ var width = bounds && bounds.halfExtents[0] * 2 || 1;
580
+ var height = bounds && bounds.halfExtents[1] * 2 || 1;
581
+ var min = bounds && bounds.min || [0, 0];
582
+ color = imagePool.getOrCreateGradient(_objectSpread(_objectSpread({
583
+ type: parsedColor.type
584
+ }, parsedColor.value), {}, {
585
+ min: min,
586
+ width: width,
587
+ height: height
588
+ }), context);
589
+ }
590
+ return color;
591
+ }
592
+
593
+ var SHADOW_NUMBER_STYLE = ['shadowBlur', 'shadowOffsetX', 'shadowOffsetY'];
594
+ var STROKE_STYLE = ['lineCap', 'lineJoin', 'miterLimit'];
595
+ var DEFAULT_STYLE = {
596
+ // common
597
+ globalAlpha: 1,
598
+ shadowBlur: 0,
599
+ shadowOffsetX: 0,
600
+ shadowOffsetY: 0,
601
+ shadowColor: '#000',
602
+ filter: 'none',
603
+ globalCompositeOperation: 'source-over',
604
+ // stroke/fill
605
+ strokeStyle: '#000',
606
+ strokeOpacity: 1,
607
+ lineWidth: 1,
608
+ lineDash: [],
609
+ lineDashOffset: 0,
610
+ lineCap: 'butt',
611
+ lineJoin: 'miter',
612
+ miterLimit: 10,
613
+ fillStyle: '#000',
614
+ fillOpacity: 1
615
+
616
+ // image
617
+ };
618
+ var defaultParsedStyle = {};
619
+
620
+ /**
621
+ * Updating the canvas context is an expensive operation. The state of the context is cached and the actual update operation is performed only when the cache is not hit.
622
+ *
623
+ * In any case, the previous value is returned, which is convenient for temporarily updating the context and restoring it later.
624
+ */
625
+ function updateContextIfNotHitCache(context, key, value, cache) {
626
+ var prevValue = cache.has(key) ? cache.get(key) : DEFAULT_STYLE[key];
627
+ if (prevValue !== value) {
628
+ // console.log('not hit cache', key, value, prevValue, cache);
629
+ if (key === 'lineDash') {
630
+ context.setLineDash(value);
631
+ } else {
632
+ // @ts-ignore
633
+ context[key] = value;
634
+ }
635
+ cache.set(key, value);
636
+ }
637
+ return prevValue;
638
+ }
639
+ var OptimizedDefaultRenderer = /*#__PURE__*/function () {
640
+ function OptimizedDefaultRenderer(imagePool) {
641
+ _classCallCheck(this, OptimizedDefaultRenderer);
642
+ this.imagePool = imagePool;
643
+ }
644
+ return _createClass(OptimizedDefaultRenderer, [{
645
+ key: "applyAttributesToContext",
646
+ value: function applyAttributesToContext(context, object) {}
647
+ }, {
648
+ key: "render",
649
+ value: function render(context, parsedStyle, object, canvasContext, plugin, runtime) {}
650
+
651
+ // #region common style
652
+ }, {
653
+ key: "applyCommonStyleToContext",
654
+ value: function applyCommonStyleToContext(context, object, forceUpdate, renderState) {
655
+ // const dpr = object.ownerDocument.defaultView.getContextService().getDPR();
656
+ var prevStyle = forceUpdate ? defaultParsedStyle : renderState.prevObject.parsedStyle;
657
+ var style = object.parsedStyle;
658
+ if (forceUpdate || style.opacity !== prevStyle.opacity) {
659
+ updateContextIfNotHitCache(context, 'globalAlpha', !isNil(style.opacity) ? style.opacity : DEFAULT_STYLE.globalAlpha, renderState.currentContext);
660
+ }
661
+
662
+ // TODO blend prop
663
+ // @ts-ignore
664
+ if (forceUpdate || style.blend !== prevStyle.blend) {
665
+ updateContextIfNotHitCache(context, 'globalCompositeOperation',
666
+ // @ts-ignore
667
+ !isNil(style.blend) ?
668
+ // @ts-ignore
669
+ style.blend : DEFAULT_STYLE.globalCompositeOperation, renderState.currentContext);
670
+ }
671
+ }
672
+ // #endregion common style
673
+
674
+ // #region stroke/fill style
675
+ }, {
676
+ key: "applyStrokeFillStyleToContext",
677
+ value: function applyStrokeFillStyleToContext(context, object, forceUpdate, renderState) {
678
+ var prevStyle = forceUpdate ? defaultParsedStyle : renderState.prevObject.parsedStyle;
679
+ var style = object.parsedStyle;
680
+ var _style$lineWidth = style.lineWidth,
681
+ lineWidth = _style$lineWidth === void 0 ? DEFAULT_STYLE.lineWidth : _style$lineWidth;
682
+ var hasFill = style.fill && !style.fill.isNone;
683
+ var hasStroke = style.stroke && !style.stroke.isNone && lineWidth > 0;
684
+ if (hasStroke) {
685
+ if (forceUpdate || object.attributes.stroke !== renderState.prevObject.attributes.stroke) {
686
+ var value = !isNil(style.stroke) && !Array.isArray(style.stroke) && !style.stroke.isNone ? object.attributes.stroke : DEFAULT_STYLE.strokeStyle;
687
+ updateContextIfNotHitCache(context, 'strokeStyle', value, renderState.currentContext);
688
+ }
689
+ if (forceUpdate || style.lineWidth !== prevStyle.lineWidth) {
690
+ updateContextIfNotHitCache(context, 'lineWidth', !isNil(style.lineWidth) ? style.lineWidth : DEFAULT_STYLE.lineWidth, renderState.currentContext);
691
+ }
692
+ if (forceUpdate || style.lineDash !== prevStyle.lineDash) {
693
+ updateContextIfNotHitCache(context, 'lineDash', style.lineDash || DEFAULT_STYLE.lineDash, renderState.currentContext);
694
+ }
695
+ if (forceUpdate || style.lineDashOffset !== prevStyle.lineDashOffset) {
696
+ updateContextIfNotHitCache(context, 'lineDashOffset', !isNil(style.lineDashOffset) ? style.lineDashOffset : DEFAULT_STYLE.lineDashOffset, renderState.currentContext);
697
+ }
698
+ for (var i = 0; i < STROKE_STYLE.length; i++) {
699
+ var styleName = STROKE_STYLE[i];
700
+ if (forceUpdate || style[styleName] !== prevStyle[styleName]) {
701
+ updateContextIfNotHitCache(context, styleName, !isNil(style[styleName]) ? style[styleName] : DEFAULT_STYLE[styleName], renderState.currentContext);
702
+ }
703
+ }
704
+ }
705
+ if (hasFill && (forceUpdate || object.attributes.fill !== renderState.prevObject.attributes.fill)) {
706
+ var _value = !isNil(style.fill) && !Array.isArray(style.fill) && !style.fill.isNone ? object.attributes.fill : DEFAULT_STYLE.fillStyle;
707
+ updateContextIfNotHitCache(context, 'fillStyle', _value, renderState.currentContext);
708
+ }
709
+ }
710
+ // #endregion stroke/fill style
711
+ }, {
712
+ key: "applyStyleToContext",
713
+ value: function applyStyleToContext(context, object, forceUpdate, renderState) {
714
+ var nodeName = object.nodeName;
715
+ this.applyCommonStyleToContext(context, object, forceUpdate, renderState);
716
+ if (nodeName === Shape.IMAGE) ; else {
717
+ this.applyStrokeFillStyleToContext(context, object, forceUpdate, renderState);
718
+ }
719
+ }
720
+ }, {
721
+ key: "applyShadowAndFilterStyleToContext",
722
+ value: function applyShadowAndFilterStyleToContext(context, object, hasShadow, renderState) {
723
+ var style = object.parsedStyle;
724
+ if (hasShadow) {
725
+ updateContextIfNotHitCache(context, 'shadowColor', style.shadowColor.toString(), renderState.currentContext);
726
+ for (var i = 0; i < SHADOW_NUMBER_STYLE.length; i++) {
727
+ var styleName = SHADOW_NUMBER_STYLE[i];
728
+ updateContextIfNotHitCache(context, styleName, style[styleName] || DEFAULT_STYLE[styleName], renderState.currentContext);
729
+ }
730
+ }
731
+ if (style.filter && style.filter.length) {
732
+ updateContextIfNotHitCache(context, 'filter',
733
+ // use raw filter string
734
+ object.attributes.filter, renderState.currentContext);
735
+ }
736
+ }
737
+ }, {
738
+ key: "clearShadowAndFilterStyleForContext",
739
+ value: function clearShadowAndFilterStyleForContext(context, hasShadow, hasFilter, renderState) {
740
+ var onlyClearShadowFilter = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
741
+ if (hasShadow) {
742
+ updateContextIfNotHitCache(context, 'shadowColor', DEFAULT_STYLE.shadowColor, renderState.currentContext);
743
+ for (var i = 0; i < SHADOW_NUMBER_STYLE.length; i++) {
744
+ var styleName = SHADOW_NUMBER_STYLE[i];
745
+ updateContextIfNotHitCache(context, styleName, DEFAULT_STYLE[styleName], renderState.currentContext);
746
+ }
747
+ }
748
+ if (hasFilter) {
749
+ if (hasShadow && onlyClearShadowFilter) {
750
+ // save drop-shadow filter
751
+ var oldFilter = context.filter;
752
+ if (!isNil(oldFilter) && oldFilter.indexOf('drop-shadow') > -1) {
753
+ updateContextIfNotHitCache(context, 'filter', oldFilter.replace(/drop-shadow\([^)]*\)/, '').trim() || DEFAULT_STYLE.filter, renderState.currentContext);
754
+ }
755
+ } else {
756
+ updateContextIfNotHitCache(context, 'filter', DEFAULT_STYLE.filter, renderState.currentContext);
757
+ }
758
+ }
759
+ }
760
+ }, {
761
+ key: "fillToContext",
762
+ value: function fillToContext(context, object, renderState, plugin, runtime) {
763
+ var _this = this;
764
+ var _object$parsedStyle = object.parsedStyle,
765
+ fill = _object$parsedStyle.fill,
766
+ fillRule = _object$parsedStyle.fillRule;
767
+ var resetStyle = null;
768
+ if (Array.isArray(fill) && fill.length > 0) {
769
+ fill.forEach(function (gradient) {
770
+ var prevStyle = updateContextIfNotHitCache(context, 'fillStyle', getColor(gradient, object, context, _this.imagePool), renderState.currentContext);
771
+ resetStyle = resetStyle !== null && resetStyle !== void 0 ? resetStyle : prevStyle;
772
+ if (fillRule) {
773
+ context.fill(fillRule);
774
+ } else {
775
+ context.fill();
776
+ }
777
+ });
778
+ } else {
779
+ if (isPattern(fill)) {
780
+ var pattern = getPattern(fill, object, context, object.ownerDocument.defaultView.context, plugin, runtime, this.imagePool);
781
+ if (pattern) {
782
+ context.fillStyle = pattern;
783
+ resetStyle = true;
784
+ }
785
+ }
786
+ if (fillRule) {
787
+ context.fill(fillRule);
788
+ } else {
789
+ context.fill();
790
+ }
791
+ }
792
+ if (resetStyle !== null) {
793
+ updateContextIfNotHitCache(context, 'fillStyle', resetStyle, renderState.currentContext);
794
+ }
795
+ }
796
+ }, {
797
+ key: "strokeToContext",
798
+ value: function strokeToContext(context, object, renderState, plugin, runtime) {
799
+ var _this2 = this;
800
+ var stroke = object.parsedStyle.stroke;
801
+ var resetStyle = null;
802
+ if (Array.isArray(stroke) && stroke.length > 0) {
803
+ stroke.forEach(function (gradient) {
804
+ var prevStyle = updateContextIfNotHitCache(context, 'strokeStyle', getColor(gradient, object, context, _this2.imagePool), renderState.currentContext);
805
+ resetStyle = resetStyle !== null && resetStyle !== void 0 ? resetStyle : prevStyle;
806
+ context.stroke();
807
+ });
808
+ } else {
809
+ if (isPattern(stroke)) {
810
+ var pattern = getPattern(stroke, object, context, object.ownerDocument.defaultView.context, plugin, runtime, this.imagePool);
811
+ if (pattern) {
812
+ var prevStyle = updateContextIfNotHitCache(context, 'strokeStyle', pattern, renderState.currentContext);
813
+ resetStyle = resetStyle !== null && resetStyle !== void 0 ? resetStyle : prevStyle;
814
+ }
815
+ }
816
+ context.stroke();
817
+ }
818
+ if (resetStyle !== null) {
819
+ updateContextIfNotHitCache(context, 'strokeStyle', resetStyle, renderState.currentContext);
820
+ }
821
+ }
822
+ }, {
823
+ key: "drawToContext",
824
+ value: function drawToContext(context, object, renderState, plugin, runtime) {
825
+ var _style$fill;
826
+ var nodeName = object.nodeName;
827
+ var style = object.parsedStyle;
828
+ var _style$opacity = style.opacity,
829
+ opacity = _style$opacity === void 0 ? DEFAULT_STYLE.globalAlpha : _style$opacity,
830
+ _style$fillOpacity = style.fillOpacity,
831
+ fillOpacity = _style$fillOpacity === void 0 ? DEFAULT_STYLE.fillOpacity : _style$fillOpacity,
832
+ _style$strokeOpacity = style.strokeOpacity,
833
+ strokeOpacity = _style$strokeOpacity === void 0 ? DEFAULT_STYLE.strokeOpacity : _style$strokeOpacity,
834
+ _style$lineWidth2 = style.lineWidth,
835
+ lineWidth = _style$lineWidth2 === void 0 ? DEFAULT_STYLE.lineWidth : _style$lineWidth2;
836
+ var hasFill = style.fill && !style.fill.isNone;
837
+ var hasStroke = style.stroke && !style.stroke.isNone && lineWidth > 0;
838
+ if (!hasFill && !hasStroke) {
839
+ return;
840
+ }
841
+ var hasShadow = !isNil(style.shadowColor) && style.shadowBlur > 0;
842
+ var isInnerShadow = style.shadowType === 'inner';
843
+ var isFillTransparent = ((_style$fill = style.fill) === null || _style$fill === void 0 ? void 0 : _style$fill.alpha) === 0;
844
+ var hasFilter = !!(style.filter && style.filter.length);
845
+ // Shadows can only be applied to fill() or stroke(), the default is fill()
846
+ var shouldDrawShadowWithStroke = hasShadow && hasStroke && (nodeName === Shape.PATH || nodeName === Shape.LINE || nodeName === Shape.POLYLINE || isFillTransparent || isInnerShadow);
847
+
848
+ // TODO https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/paint-order
849
+
850
+ var originGlobalAlpha = null;
851
+ if (hasFill) {
852
+ if (!shouldDrawShadowWithStroke) {
853
+ this.applyShadowAndFilterStyleToContext(context, object, hasShadow, renderState);
854
+ }
855
+ var updateOpacity = opacity * fillOpacity;
856
+ originGlobalAlpha = updateContextIfNotHitCache(context, 'globalAlpha', updateOpacity, renderState.currentContext);
857
+ this.fillToContext(context, object, renderState, plugin, runtime);
858
+ if (!shouldDrawShadowWithStroke) {
859
+ this.clearShadowAndFilterStyleForContext(context, hasShadow, hasFilter, renderState);
860
+ }
861
+ }
862
+ if (hasStroke) {
863
+ var clearShadowAndFilter = false;
864
+ var _updateOpacity = opacity * strokeOpacity;
865
+ var prevOpacity = updateContextIfNotHitCache(context, 'globalAlpha', _updateOpacity, renderState.currentContext);
866
+ originGlobalAlpha = hasFill ? originGlobalAlpha : prevOpacity;
867
+ if (shouldDrawShadowWithStroke) {
868
+ this.applyShadowAndFilterStyleToContext(context, object, hasShadow, renderState);
869
+ clearShadowAndFilter = true;
870
+ if (isInnerShadow) {
871
+ var originBlend = context.globalCompositeOperation;
872
+ context.globalCompositeOperation = 'source-atop';
873
+ this.strokeToContext(context, object, renderState, plugin, runtime);
874
+ context.globalCompositeOperation = originBlend;
875
+ this.clearShadowAndFilterStyleForContext(context, hasShadow, hasFilter, renderState, true);
876
+ }
877
+ }
878
+ this.strokeToContext(context, object, renderState, plugin, runtime);
879
+ if (clearShadowAndFilter) {
880
+ this.clearShadowAndFilterStyleForContext(context, hasShadow, hasFilter, renderState);
881
+ }
882
+ }
883
+
884
+ // clear
885
+ if (originGlobalAlpha !== null) {
886
+ updateContextIfNotHitCache(context, 'globalAlpha', originGlobalAlpha, renderState.currentContext);
887
+ }
888
+ }
889
+ }]);
890
+ }();
891
+
892
+ var DefaultRenderer = /*#__PURE__*/function (_OptimizedDefaultRend) {
893
+ function DefaultRenderer() {
894
+ _classCallCheck(this, DefaultRenderer);
895
+ return _callSuper(this, DefaultRenderer, arguments);
896
+ }
897
+ _inherits(DefaultRenderer, _OptimizedDefaultRend);
898
+ return _createClass(DefaultRenderer, [{
899
+ key: "render",
900
+ value: function render(context, parsedStyle, object, canvasContext, plugin, runtime) {
901
+ var fill = parsedStyle.fill,
902
+ fillRule = parsedStyle.fillRule,
903
+ _parsedStyle$opacity = parsedStyle.opacity,
904
+ opacity = _parsedStyle$opacity === void 0 ? 1 : _parsedStyle$opacity,
905
+ _parsedStyle$fillOpac = parsedStyle.fillOpacity,
906
+ fillOpacity = _parsedStyle$fillOpac === void 0 ? 1 : _parsedStyle$fillOpac,
907
+ stroke = parsedStyle.stroke,
908
+ _parsedStyle$strokeOp = parsedStyle.strokeOpacity,
909
+ strokeOpacity = _parsedStyle$strokeOp === void 0 ? 1 : _parsedStyle$strokeOp,
910
+ _parsedStyle$lineWidt = parsedStyle.lineWidth,
911
+ lineWidth = _parsedStyle$lineWidt === void 0 ? 1 : _parsedStyle$lineWidt,
912
+ lineCap = parsedStyle.lineCap,
913
+ lineJoin = parsedStyle.lineJoin,
914
+ shadowType = parsedStyle.shadowType,
915
+ shadowColor = parsedStyle.shadowColor,
916
+ shadowBlur = parsedStyle.shadowBlur,
917
+ filter = parsedStyle.filter,
918
+ miterLimit = parsedStyle.miterLimit;
919
+ var hasFill = fill && !fill.isNone;
920
+ var hasStroke = stroke && !stroke.isNone && lineWidth > 0;
921
+ var isFillTransparent = (fill === null || fill === void 0 ? void 0 : fill.alpha) === 0;
922
+ var hasFilter = !!(filter && filter.length);
923
+ var hasShadow = !isNil(shadowColor) && shadowBlur > 0;
924
+ var nodeName = object.nodeName;
925
+ var isInnerShadow = shadowType === 'inner';
926
+ var shouldDrawShadowWithStroke = hasStroke && hasShadow && (nodeName === Shape.PATH || nodeName === Shape.LINE || nodeName === Shape.POLYLINE || isFillTransparent || isInnerShadow);
927
+ if (hasFill) {
928
+ context.globalAlpha = opacity * fillOpacity;
929
+ if (!shouldDrawShadowWithStroke) {
930
+ setShadowAndFilter(object, context, hasShadow);
931
+ }
932
+ applyFill(context, object, fill, fillRule, canvasContext, plugin, runtime, this.imagePool);
933
+ if (!shouldDrawShadowWithStroke) {
934
+ this.clearShadowAndFilter(context, hasFilter, hasShadow);
935
+ }
936
+ }
937
+ if (hasStroke) {
938
+ context.globalAlpha = opacity * strokeOpacity;
939
+ context.lineWidth = lineWidth;
940
+ if (!isNil(miterLimit)) {
941
+ context.miterLimit = miterLimit;
942
+ }
943
+ if (!isNil(lineCap)) {
944
+ context.lineCap = lineCap;
945
+ }
946
+ if (!isNil(lineJoin)) {
947
+ context.lineJoin = lineJoin;
948
+ }
949
+ if (shouldDrawShadowWithStroke) {
950
+ if (isInnerShadow) {
951
+ context.globalCompositeOperation = 'source-atop';
952
+ }
953
+ setShadowAndFilter(object, context, true);
954
+ if (isInnerShadow) {
955
+ applyStroke(context, object, stroke, canvasContext, plugin, runtime, this.imagePool);
956
+ context.globalCompositeOperation = DEFAULT_STYLE.globalCompositeOperation;
957
+ this.clearShadowAndFilter(context, hasFilter, true);
958
+ }
959
+ }
960
+ applyStroke(context, object, stroke, canvasContext, plugin, runtime, this.imagePool);
961
+ }
962
+ }
963
+ }, {
964
+ key: "clearShadowAndFilter",
965
+ value: function clearShadowAndFilter(context, hasFilter, hasShadow) {
966
+ if (hasShadow) {
967
+ context.shadowColor = 'transparent';
968
+ context.shadowBlur = 0;
969
+ }
970
+ if (hasFilter) {
971
+ // save drop-shadow filter
972
+ var oldFilter = context.filter;
973
+ if (!isNil(oldFilter) && oldFilter.indexOf('drop-shadow') > -1) {
974
+ context.filter = oldFilter.replace(/drop-shadow\([^)]*\)/, '').trim() || 'none';
975
+ }
976
+ }
977
+ }
978
+ }]);
979
+ }(OptimizedDefaultRenderer);
980
+
981
+ /**
982
+ * apply before fill and stroke but only once
983
+ */
984
+ function setShadowAndFilter(object, context, hasShadow) {
985
+ var _object$parsedStyle = object.parsedStyle,
986
+ filter = _object$parsedStyle.filter,
987
+ shadowColor = _object$parsedStyle.shadowColor,
988
+ shadowBlur = _object$parsedStyle.shadowBlur,
989
+ shadowOffsetX = _object$parsedStyle.shadowOffsetX,
990
+ shadowOffsetY = _object$parsedStyle.shadowOffsetY;
991
+ if (filter && filter.length) {
992
+ // use raw filter string
993
+ context.filter = object.style.filter;
994
+ }
995
+ if (hasShadow) {
996
+ context.shadowColor = shadowColor.toString();
997
+ context.shadowBlur = shadowBlur || 0;
998
+ context.shadowOffsetX = shadowOffsetX || 0;
999
+ context.shadowOffsetY = shadowOffsetY || 0;
1000
+ }
1001
+ }
1002
+ function applyFill(context, object, fill, fillRule, canvasContext, plugin, runtime, imagePool) {
1003
+ var skipFill = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : false;
1004
+ if (Array.isArray(fill)) {
1005
+ fill.forEach(function (gradient) {
1006
+ context.fillStyle = getColor(gradient, object, context, imagePool);
1007
+ if (!skipFill) {
1008
+ fillRule ? context.fill(fillRule) : context.fill();
1009
+ }
1010
+ });
1011
+ } else {
1012
+ if (isPattern(fill)) {
1013
+ context.fillStyle = getPattern(fill, object, context, canvasContext, plugin, runtime, imagePool);
1014
+ }
1015
+ if (!skipFill) {
1016
+ fillRule ? context.fill(fillRule) : context.fill();
1017
+ }
1018
+ }
1019
+ }
1020
+ function applyStroke(context, object, stroke, canvasContext, plugin, runtime, imagePool) {
1021
+ var skipStroke = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : false;
1022
+ if (Array.isArray(stroke)) {
1023
+ stroke.forEach(function (gradient) {
1024
+ context.strokeStyle = getColor(gradient, object, context, imagePool);
1025
+ if (!skipStroke) {
1026
+ context.stroke();
1027
+ }
1028
+ });
1029
+ } else {
1030
+ if (isPattern(stroke)) {
1031
+ context.strokeStyle = getPattern(stroke, object, context, canvasContext, plugin, runtime, imagePool);
1032
+ }
1033
+ if (!skipStroke) {
1034
+ context.stroke();
1035
+ }
1036
+ }
1037
+ }
1038
+
1039
+ function calculateOverlapRect(rect1, rect2) {
1040
+ var _rect = _slicedToArray(rect1, 4),
1041
+ x1 = _rect[0],
1042
+ y1 = _rect[1],
1043
+ w1 = _rect[2],
1044
+ h1 = _rect[3];
1045
+ var _rect2 = _slicedToArray(rect2, 4),
1046
+ x2 = _rect2[0],
1047
+ y2 = _rect2[1],
1048
+ w2 = _rect2[2],
1049
+ h2 = _rect2[3];
1050
+
1051
+ // 计算重叠区域的左上角和右下角
1052
+ var overlapLeft = Math.max(x1, x2);
1053
+ var overlapTop = Math.max(y1, y2);
1054
+ var overlapRight = Math.min(x1 + w1, x2 + w2);
1055
+ var overlapBottom = Math.min(y1 + h1, y2 + h2);
1056
+ if (overlapRight <= overlapLeft || overlapBottom <= overlapTop) {
1057
+ return null;
1058
+ }
1059
+ return [overlapLeft, overlapTop, overlapRight - overlapLeft, overlapBottom - overlapTop];
1060
+ }
1061
+ function transformRect(rect, matrix) {
1062
+ var tl = vec3.transformMat4(vec3.create(), [rect[0], rect[1], 0], matrix);
1063
+ var tr = vec3.transformMat4(vec3.create(), [rect[0] + rect[2], rect[1], 0], matrix);
1064
+ var bl = vec3.transformMat4(vec3.create(), [rect[0], rect[1] + rect[3], 0], matrix);
1065
+ var br = vec3.transformMat4(vec3.create(), [rect[0] + rect[2], rect[1] + rect[3], 0], matrix);
1066
+ return [Math.min(tl[0], tr[0], bl[0], br[0]), Math.min(tl[1], tr[1], bl[1], br[1]), Math.max(tl[0], tr[0], bl[0], br[0]) - Math.min(tl[0], tr[0], bl[0], br[0]), Math.max(tl[1], tr[1], bl[1], br[1]) - Math.min(tl[1], tr[1], bl[1], br[1])];
1067
+ }
1068
+
1069
+ var ImageRenderer = /*#__PURE__*/function (_DefaultRenderer) {
1070
+ function ImageRenderer() {
1071
+ _classCallCheck(this, ImageRenderer);
1072
+ return _callSuper(this, ImageRenderer, arguments);
1073
+ }
1074
+ _inherits(ImageRenderer, _DefaultRenderer);
1075
+ return _createClass(ImageRenderer, [{
1076
+ key: "renderDownSampled",
1077
+ value: function renderDownSampled(context, parsedStyle, object, data) {
1078
+ var src = data.src,
1079
+ imageCache = data.imageCache;
1080
+ if (!imageCache.downSampled) {
1081
+ this.imagePool.createDownSampledImage(src, object).then(function () {
1082
+ // be removed from dom tree
1083
+ if (!object.ownerDocument) {
1084
+ return;
1085
+ }
1086
+
1087
+ // rerender
1088
+ object.dirty();
1089
+ object.ownerDocument.defaultView.context.renderingService.dirty();
1090
+ })["catch"](function (reason) {
1091
+ console.error(reason);
1092
+ });
1093
+ return;
1094
+ }
1095
+ context.drawImage(imageCache.downSampled, Math.floor(data.drawRect[0]), Math.floor(data.drawRect[1]), Math.ceil(data.drawRect[2]), Math.ceil(data.drawRect[3]));
1096
+ }
1097
+ }, {
1098
+ key: "renderTile",
1099
+ value: function renderTile(context, parsedStyle, object, data) {
1100
+ var src = data.src,
1101
+ imageCache = data.imageCache,
1102
+ imageRect = data.imageRect,
1103
+ drawRect = data.drawRect;
1104
+ var originalSize = imageCache.size;
1105
+ var _context$getTransform = context.getTransform(),
1106
+ a = _context$getTransform.a,
1107
+ b = _context$getTransform.b,
1108
+ c = _context$getTransform.c,
1109
+ d = _context$getTransform.d,
1110
+ e = _context$getTransform.e,
1111
+ f = _context$getTransform.f;
1112
+ context.resetTransform();
1113
+ if (!(imageCache !== null && imageCache !== void 0 && imageCache.gridSize)) {
1114
+ this.imagePool.createImageTiles(src, [], function () {
1115
+ // be removed from dom tree
1116
+ if (!object.ownerDocument) {
1117
+ return;
1118
+ }
1119
+
1120
+ // rerender
1121
+ object.dirty();
1122
+ object.ownerDocument.defaultView.context.renderingService.dirty();
1123
+ }, object)["catch"](function (reason) {
1124
+ console.error(reason);
1125
+ });
1126
+ return;
1127
+ }
1128
+ var scaleToOrigin = [originalSize[0] / imageRect[2], originalSize[1] / imageRect[3]];
1129
+ var scaledTileSize = [imageCache.tileSize[0] / scaleToOrigin[0], imageCache.tileSize[1] / scaleToOrigin[1]];
1130
+ var _ref = [Math.floor((drawRect[0] - imageRect[0]) / scaledTileSize[0]), Math.ceil((drawRect[0] + drawRect[2] - imageRect[0]) / scaledTileSize[0])],
1131
+ startTileX = _ref[0],
1132
+ endTileX = _ref[1];
1133
+ var _ref2 = [Math.floor((drawRect[1] - imageRect[1]) / scaledTileSize[1]), Math.ceil((drawRect[1] + drawRect[3] - imageRect[1]) / scaledTileSize[1])],
1134
+ startTileY = _ref2[0],
1135
+ endTileY = _ref2[1];
1136
+ for (var tileY = startTileY; tileY <= endTileY; tileY++) {
1137
+ for (var tileX = startTileX; tileX <= endTileX; tileX++) {
1138
+ var item = imageCache.tiles[tileY][tileX];
1139
+ if (item) {
1140
+ var tileRect = [Math.floor(imageRect[0] + item.tileX * scaledTileSize[0]), Math.floor(imageRect[1] + item.tileY * scaledTileSize[1]), Math.ceil(scaledTileSize[0]), Math.ceil(scaledTileSize[1])];
1141
+ context.drawImage(item.data, tileRect[0], tileRect[1], tileRect[2], tileRect[3]);
1142
+ }
1143
+ }
1144
+ }
1145
+ context.setTransform(a, b, c, d, e, f);
1146
+ }
1147
+ }, {
1148
+ key: "render",
1149
+ value: function render(context, parsedStyle, object) {
1150
+ var _parsedStyle$x = parsedStyle.x,
1151
+ x = _parsedStyle$x === void 0 ? 0 : _parsedStyle$x,
1152
+ _parsedStyle$y = parsedStyle.y,
1153
+ y = _parsedStyle$y === void 0 ? 0 : _parsedStyle$y,
1154
+ width = parsedStyle.width,
1155
+ height = parsedStyle.height,
1156
+ src = parsedStyle.src,
1157
+ shadowColor = parsedStyle.shadowColor,
1158
+ shadowBlur = parsedStyle.shadowBlur;
1159
+ var imageCache = this.imagePool.getImageSync(src, object);
1160
+ var image = imageCache === null || imageCache === void 0 ? void 0 : imageCache.img;
1161
+ var iw = width;
1162
+ var ih = height;
1163
+ if (!image) {
1164
+ return;
1165
+ }
1166
+ iw || (iw = image.width);
1167
+ ih || (ih = image.height);
1168
+ var hasShadow = !isNil(shadowColor) && shadowBlur > 0;
1169
+ setShadowAndFilter(object, context, hasShadow);
1170
+
1171
+ // node-canvas will throw the following err:
1172
+ // Error: Image given has not completed loading
1173
+ try {
1174
+ var _object$ownerDocument = object.ownerDocument.defaultView.getContextService().getDomElement(),
1175
+ viewWidth = _object$ownerDocument.width,
1176
+ viewHeight = _object$ownerDocument.height;
1177
+ var currentTransform = context.getTransform();
1178
+ var a = currentTransform.a,
1179
+ b = currentTransform.b,
1180
+ c = currentTransform.c,
1181
+ d = currentTransform.d,
1182
+ e = currentTransform.e,
1183
+ f = currentTransform.f;
1184
+ // 构建 mat4 矩阵
1185
+ // prettier-ignore
1186
+ var transformMatrix = mat4.fromValues(a, c, 0, 0, b, d, 0, 0, 0, 0, 1, 0, e, f, 0, 1);
1187
+ var imageRect = transformRect([x, y, iw, ih], transformMatrix);
1188
+ var drawRect = calculateOverlapRect([0, 0, viewWidth, viewHeight], imageRect);
1189
+ if (!drawRect) {
1190
+ return;
1191
+ }
1192
+ if (!object.ownerDocument.defaultView.getConfig().enableLargeImageOptimization) {
1193
+ ImageRenderer.renderFull(context, parsedStyle, object, {
1194
+ image: image,
1195
+ drawRect: [x, y, iw, ih]
1196
+ });
1197
+ return;
1198
+ }
1199
+ var sizeOfOrigin = imageRect[2] / imageCache.size[0];
1200
+ if (sizeOfOrigin < (imageCache.downSamplingRate || 0.5)) {
1201
+ this.renderDownSampled(context, parsedStyle, object, {
1202
+ src: src,
1203
+ imageCache: imageCache,
1204
+ drawRect: [x, y, iw, ih]
1205
+ });
1206
+ return;
1207
+ }
1208
+ if (!ImagePool.isSupportTile) {
1209
+ ImageRenderer.renderFull(context, parsedStyle, object, {
1210
+ image: image,
1211
+ drawRect: [x, y, iw, ih]
1212
+ });
1213
+ return;
1214
+ }
1215
+ this.renderTile(context, parsedStyle, object, {
1216
+ src: src,
1217
+ imageCache: imageCache,
1218
+ imageRect: imageRect,
1219
+ drawRect: drawRect
1220
+ });
1221
+ } catch (_unused) {
1222
+ // expected error
1223
+ }
1224
+ }
1225
+
1226
+ // ---
1227
+ }, {
1228
+ key: "drawToContext",
1229
+ value: function drawToContext(context, object, renderState, plugin, runtime) {
1230
+ this.render(context, object.parsedStyle, object);
1231
+ }
1232
+ }], [{
1233
+ key: "renderFull",
1234
+ value: function renderFull(context, parsedStyle, object, data) {
1235
+ context.drawImage(data.image, Math.floor(data.drawRect[0]), Math.floor(data.drawRect[1]), Math.ceil(data.drawRect[2]), Math.ceil(data.drawRect[3]));
1236
+ }
1237
+ }]);
1238
+ }(DefaultRenderer);
1239
+
1240
+ var TextRenderer = /*#__PURE__*/function (_DefaultRenderer) {
1241
+ function TextRenderer() {
1242
+ _classCallCheck(this, TextRenderer);
1243
+ return _callSuper(this, TextRenderer, arguments);
1244
+ }
1245
+ _inherits(TextRenderer, _DefaultRenderer);
1246
+ return _createClass(TextRenderer, [{
1247
+ key: "render",
1248
+ value: function render(context, parsedStyle, object, canvasContext, plugin, runtime) {
1249
+ // Trigger text geometry calculation.
1250
+ object.getBounds();
1251
+ var _parsedStyle$lineWidt = parsedStyle.lineWidth,
1252
+ lineWidth = _parsedStyle$lineWidt === void 0 ? 1 : _parsedStyle$lineWidt,
1253
+ _parsedStyle$textAlig = parsedStyle.textAlign,
1254
+ textAlign = _parsedStyle$textAlig === void 0 ? 'start' : _parsedStyle$textAlig,
1255
+ _parsedStyle$textBase = parsedStyle.textBaseline,
1256
+ textBaseline = _parsedStyle$textBase === void 0 ? 'alphabetic' : _parsedStyle$textBase,
1257
+ _parsedStyle$lineJoin = parsedStyle.lineJoin,
1258
+ lineJoin = _parsedStyle$lineJoin === void 0 ? 'miter' : _parsedStyle$lineJoin,
1259
+ _parsedStyle$miterLim = parsedStyle.miterLimit,
1260
+ miterLimit = _parsedStyle$miterLim === void 0 ? 10 : _parsedStyle$miterLim,
1261
+ _parsedStyle$letterSp = parsedStyle.letterSpacing,
1262
+ letterSpacing = _parsedStyle$letterSp === void 0 ? 0 : _parsedStyle$letterSp,
1263
+ stroke = parsedStyle.stroke,
1264
+ fill = parsedStyle.fill,
1265
+ fillRule = parsedStyle.fillRule,
1266
+ _parsedStyle$fillOpac = parsedStyle.fillOpacity,
1267
+ fillOpacity = _parsedStyle$fillOpac === void 0 ? 1 : _parsedStyle$fillOpac,
1268
+ _parsedStyle$strokeOp = parsedStyle.strokeOpacity,
1269
+ strokeOpacity = _parsedStyle$strokeOp === void 0 ? 1 : _parsedStyle$strokeOp,
1270
+ _parsedStyle$opacity = parsedStyle.opacity,
1271
+ opacity = _parsedStyle$opacity === void 0 ? 1 : _parsedStyle$opacity,
1272
+ metrics = parsedStyle.metrics,
1273
+ _parsedStyle$x = parsedStyle.x,
1274
+ x = _parsedStyle$x === void 0 ? 0 : _parsedStyle$x,
1275
+ _parsedStyle$y = parsedStyle.y,
1276
+ y = _parsedStyle$y === void 0 ? 0 : _parsedStyle$y,
1277
+ dx = parsedStyle.dx,
1278
+ dy = parsedStyle.dy,
1279
+ shadowColor = parsedStyle.shadowColor,
1280
+ shadowBlur = parsedStyle.shadowBlur,
1281
+ textDecorationLine = parsedStyle.textDecorationLine;
1282
+ var font = metrics.font,
1283
+ lines = metrics.lines,
1284
+ height = metrics.height,
1285
+ lineHeight = metrics.lineHeight,
1286
+ lineMetrics = metrics.lineMetrics;
1287
+ context.font = font;
1288
+ context.lineWidth = lineWidth;
1289
+ context.textAlign = textAlign === 'middle' ? 'center' : textAlign;
1290
+ var formattedTextBaseline = textBaseline;
1291
+ if (formattedTextBaseline === 'alphabetic') {
1292
+ formattedTextBaseline = 'bottom';
1293
+ }
1294
+ context.lineJoin = lineJoin;
1295
+ if (!isNil(miterLimit)) {
1296
+ context.miterLimit = miterLimit;
1297
+ }
1298
+ var linePositionY = y;
1299
+ // handle vertical text baseline
1300
+ if (textBaseline === 'middle') {
1301
+ linePositionY += -height / 2 - lineHeight / 2;
1302
+ } else if (textBaseline === 'bottom' || textBaseline === 'alphabetic' || textBaseline === 'ideographic') {
1303
+ linePositionY += -height;
1304
+ } else if (textBaseline === 'top' || textBaseline === 'hanging') {
1305
+ linePositionY += -lineHeight;
1306
+ }
1307
+
1308
+ // account for dx & dy
1309
+ var offsetX = x + (dx || 0);
1310
+ linePositionY += dy || 0;
1311
+ if (lines.length === 1) {
1312
+ if (formattedTextBaseline === 'bottom') {
1313
+ formattedTextBaseline = 'middle';
1314
+ linePositionY -= 0.5 * height;
1315
+ } else if (formattedTextBaseline === 'top') {
1316
+ formattedTextBaseline = 'middle';
1317
+ linePositionY += 0.5 * height;
1318
+ }
1319
+ }
1320
+ context.textBaseline = formattedTextBaseline;
1321
+ var hasShadow = !isNil(shadowColor) && shadowBlur > 0;
1322
+ setShadowAndFilter(object, context, hasShadow);
1323
+
1324
+ // draw lines line by line
1325
+ for (var i = 0; i < lines.length; i++) {
1326
+ var linePositionX = lineWidth / 2 + offsetX;
1327
+ linePositionY += lineHeight;
1328
+
1329
+ // no need to re-position X, cause we already set text align
1330
+ // @see https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/textAlign
1331
+ if (!isNil(stroke) && !stroke.isNone && lineWidth) {
1332
+ this.drawLetterSpacing(context, object, lines[i], lineMetrics[i], textAlign, linePositionX, linePositionY, letterSpacing, fill, fillRule, fillOpacity, stroke, strokeOpacity, opacity, true, canvasContext, plugin, runtime);
1333
+ }
1334
+ if (!isNil(fill)) {
1335
+ this.drawLetterSpacing(context, object, lines[i], lineMetrics[i], textAlign, linePositionX, linePositionY, letterSpacing, fill, fillRule, fillOpacity, stroke, strokeOpacity, opacity, false, canvasContext, plugin, runtime);
1336
+ }
1337
+ }
1338
+
1339
+ // Draw text decoration lines
1340
+ if (textDecorationLine && textDecorationLine !== 'none') {
1341
+ this.drawTextDecorations(context, parsedStyle, object, lines, lineHeight, offsetX, y + (dy || 0), canvasContext, plugin, runtime);
1342
+ }
1343
+ }
1344
+ }, {
1345
+ key: "drawLetterSpacing",
1346
+ value: function drawLetterSpacing(context, object, text, lineMetrics, textAlign, x, y, letterSpacing, fill, fillRule, fillOpacity, stroke, strokeOpacity, opacity, isStroke, canvasContext, plugin, runtime) {
1347
+ // letterSpacing of 0 means normal, render all texts directly
1348
+ if (letterSpacing === 0) {
1349
+ if (isStroke) {
1350
+ this.strokeText(context, object, text, x, y, stroke, strokeOpacity, canvasContext, plugin, runtime);
1351
+ } else {
1352
+ this.fillText(context, object, text, x, y, fill, fillRule, fillOpacity, opacity, canvasContext, plugin, runtime);
1353
+ }
1354
+ return;
1355
+ }
1356
+
1357
+ // draw text using left align
1358
+ var currentTextAlign = context.textAlign;
1359
+ context.textAlign = 'left';
1360
+ var currentPosition = x;
1361
+ if (textAlign === 'center' || textAlign === 'middle') {
1362
+ currentPosition = x - lineMetrics.width / 2;
1363
+ } else if (textAlign === 'right' || textAlign === 'end') {
1364
+ currentPosition = x - lineMetrics.width;
1365
+ }
1366
+ var stringArray = Array.from(text);
1367
+ var previousWidth = context.measureText(text).width;
1368
+ var currentWidth = 0;
1369
+ for (var i = 0; i < stringArray.length; ++i) {
1370
+ var currentChar = stringArray[i];
1371
+ if (isStroke) {
1372
+ this.strokeText(context, object, currentChar, currentPosition, y, stroke, strokeOpacity, canvasContext, plugin, runtime);
1373
+ } else {
1374
+ this.fillText(context, object, currentChar, currentPosition, y, fill, fillRule, fillOpacity, opacity, canvasContext, plugin, runtime);
1375
+ }
1376
+ currentWidth = context.measureText(text.substring(i + 1)).width;
1377
+ currentPosition += previousWidth - currentWidth + letterSpacing;
1378
+ previousWidth = currentWidth;
1379
+ }
1380
+ context.textAlign = currentTextAlign;
1381
+ }
1382
+ }, {
1383
+ key: "fillText",
1384
+ value: function fillText(context, object, text, x, y, fill, fillRule, fillOpacity, opacity, canvasContext, plugin, runtime) {
1385
+ applyFill(context, object, fill, fillRule, canvasContext, plugin, runtime, this.imagePool, true);
1386
+ var currentGlobalAlpha;
1387
+ var applyOpacity = !isNil(fillOpacity) && fillOpacity !== 1;
1388
+ if (applyOpacity) {
1389
+ currentGlobalAlpha = context.globalAlpha;
1390
+ context.globalAlpha = fillOpacity * opacity;
1391
+ }
1392
+ context.fillText(text, x, y);
1393
+ if (applyOpacity) {
1394
+ context.globalAlpha = currentGlobalAlpha;
1395
+ }
1396
+ }
1397
+ }, {
1398
+ key: "strokeText",
1399
+ value: function strokeText(context, object, text, x, y, stroke, strokeOpacity, canvasContext, plugin, runtime) {
1400
+ applyStroke(context, object, stroke, canvasContext, plugin, runtime, this.imagePool, true);
1401
+ var currentGlobalAlpha;
1402
+ var applyOpacity = !isNil(strokeOpacity) && strokeOpacity !== 1;
1403
+ if (applyOpacity) {
1404
+ currentGlobalAlpha = context.globalAlpha;
1405
+ context.globalAlpha = strokeOpacity;
1406
+ }
1407
+ context.strokeText(text, x, y);
1408
+ if (applyOpacity) {
1409
+ context.globalAlpha = currentGlobalAlpha;
1410
+ }
1411
+ }
1412
+
1413
+ /**
1414
+ * Draw text decoration lines (underline, overline, line-through)
1415
+ */
1416
+ }, {
1417
+ key: "drawTextDecorations",
1418
+ value: function drawTextDecorations(context, parsedStyle, object, lines, lineHeight, offsetX, baseY, canvasContext, plugin, runtime) {
1419
+ var textDecorationLine = parsedStyle.textDecorationLine,
1420
+ textDecorationColor = parsedStyle.textDecorationColor,
1421
+ textDecorationStyle = parsedStyle.textDecorationStyle,
1422
+ _parsedStyle$textDeco = parsedStyle.textDecorationThickness,
1423
+ textDecorationThickness = _parsedStyle$textDeco === void 0 ? 1 : _parsedStyle$textDeco,
1424
+ _parsedStyle$textAlig2 = parsedStyle.textAlign,
1425
+ textAlign = _parsedStyle$textAlig2 === void 0 ? 'start' : _parsedStyle$textAlig2,
1426
+ _parsedStyle$lineWidt2 = parsedStyle.lineWidth,
1427
+ lineWidth = _parsedStyle$lineWidt2 === void 0 ? 1 : _parsedStyle$lineWidt2,
1428
+ metrics = parsedStyle.metrics;
1429
+ if (!textDecorationLine || textDecorationLine === 'none') {
1430
+ return;
1431
+ }
1432
+ var lineMetrics = metrics.lineMetrics;
1433
+ var decorations = textDecorationLine.split(' ');
1434
+
1435
+ // Set decoration style
1436
+ context.lineWidth = textDecorationThickness;
1437
+ if (textDecorationColor) {
1438
+ context.strokeStyle = "rgba(".concat(textDecorationColor.r, ", ").concat(textDecorationColor.g, ", ").concat(textDecorationColor.b, ", ").concat(textDecorationColor.alpha, ")");
1439
+ }
1440
+
1441
+ // Set line style based on textDecorationStyle
1442
+ switch (textDecorationStyle) {
1443
+ case 'dashed':
1444
+ context.setLineDash([5, 5]);
1445
+ break;
1446
+ case 'dotted':
1447
+ context.setLineDash([2, 2]);
1448
+ break;
1449
+ case 'wavy':
1450
+ // For wavy, we'll use a simple approximation with bezier curves
1451
+ // A full implementation would be more complex
1452
+ context.setLineDash([]);
1453
+ break;
1454
+ default:
1455
+ context.setLineDash([]);
1456
+ break;
1457
+ }
1458
+ var linePositionY = baseY;
1459
+
1460
+ // Adjust for text baseline
1461
+ var _parsedStyle$textBase2 = parsedStyle.textBaseline,
1462
+ textBaseline = _parsedStyle$textBase2 === void 0 ? 'alphabetic' : _parsedStyle$textBase2;
1463
+ if (textBaseline === 'middle') {
1464
+ linePositionY += -metrics.height / 2 - lineHeight / 2;
1465
+ } else if (textBaseline === 'bottom' || textBaseline === 'alphabetic' || textBaseline === 'ideographic') {
1466
+ linePositionY += -metrics.height;
1467
+ } else if (textBaseline === 'top' || textBaseline === 'hanging') {
1468
+ linePositionY += -lineHeight;
1469
+ }
1470
+
1471
+ // Draw each decoration for each line
1472
+ for (var i = 0; i < lines.length; i++) {
1473
+ linePositionY += lineHeight;
1474
+ var lineMetric = lineMetrics[i];
1475
+ if (!lineMetric) continue;
1476
+ var lineWidthOffset = lineWidth / 2;
1477
+ var startX = offsetX;
1478
+ var endX = offsetX + lineMetric.width;
1479
+
1480
+ // Adjust for text alignment
1481
+ if (textAlign === 'center' || textAlign === 'middle') {
1482
+ startX = offsetX - lineMetric.width / 2;
1483
+ endX = offsetX + lineMetric.width / 2;
1484
+ } else if (textAlign === 'right' || textAlign === 'end') {
1485
+ startX = offsetX - lineMetric.width;
1486
+ endX = offsetX;
1487
+ }
1488
+
1489
+ // Add lineWidth offset
1490
+ startX += lineWidthOffset;
1491
+ endX += lineWidthOffset;
1492
+
1493
+ // Draw each type of decoration
1494
+ var _iterator = _createForOfIteratorHelper(decorations),
1495
+ _step;
1496
+ try {
1497
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
1498
+ var decoration = _step.value;
1499
+ var decorationY = linePositionY;
1500
+ switch (decoration) {
1501
+ case 'underline':
1502
+ decorationY += 2; // Small offset below baseline
1503
+ break;
1504
+ case 'overline':
1505
+ decorationY -= lineHeight - 2; // Small offset above line
1506
+ break;
1507
+ case 'line-through':
1508
+ decorationY -= lineHeight / 2; // Middle of line
1509
+ break;
1510
+ default:
1511
+ continue;
1512
+ // Unknown decoration type
1513
+ }
1514
+ if (textDecorationStyle === 'wavy') {
1515
+ this.drawWavyLine(context, startX, endX, decorationY);
1516
+ } else {
1517
+ context.beginPath();
1518
+ context.moveTo(startX, decorationY);
1519
+ context.lineTo(endX, decorationY);
1520
+ context.stroke();
1521
+ }
1522
+ }
1523
+ } catch (err) {
1524
+ _iterator.e(err);
1525
+ } finally {
1526
+ _iterator.f();
1527
+ }
1528
+ }
1529
+
1530
+ // Reset line dash
1531
+ context.setLineDash([]);
1532
+ }
1533
+
1534
+ /**
1535
+ * Draw a wavy line as an approximation of the wavy text decoration style
1536
+ */
1537
+ }, {
1538
+ key: "drawWavyLine",
1539
+ value: function drawWavyLine(context, startX, endX, y) {
1540
+ var amplitude = 2; // Height of the wave
1541
+ var wavelength = 10; // Length of one wave cycle
1542
+ var numWaves = Math.floor((endX - startX) / wavelength);
1543
+ context.beginPath();
1544
+ context.moveTo(startX, y);
1545
+ for (var i = 0; i < numWaves; i++) {
1546
+ var x1 = startX + i * wavelength + wavelength / 4;
1547
+ var y1 = y + amplitude;
1548
+ var x2 = startX + i * wavelength + wavelength / 2;
1549
+ var y2 = y;
1550
+ context.quadraticCurveTo(x1, y1, x2, y2);
1551
+ var x3 = startX + i * wavelength + wavelength * 3 / 4;
1552
+ var y3 = y - amplitude;
1553
+ var x4 = startX + (i + 1) * wavelength;
1554
+ var y4 = y;
1555
+ context.quadraticCurveTo(x3, y3, x4, y4);
1556
+ }
1557
+ context.stroke();
1558
+ }
1559
+
1560
+ // ---
1561
+ }, {
1562
+ key: "drawToContext",
1563
+ value: function drawToContext(context, object, renderState, plugin, runtime) {
1564
+ this.render(context, object.parsedStyle, object, object.ownerDocument.defaultView.context, plugin, runtime);
1565
+ }
1566
+ }]);
1567
+ }(DefaultRenderer);
1568
+
1569
+ var Plugin$2 = /*#__PURE__*/function (_AbstractRendererPlug) {
1570
+ function Plugin() {
1571
+ var _this;
1572
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1573
+ _classCallCheck(this, Plugin);
1574
+ _this = _callSuper(this, Plugin);
1575
+ _this.name = 'canvas-renderer';
1576
+ _this.options = options;
1577
+ return _this;
1578
+ }
1579
+ _inherits(Plugin, _AbstractRendererPlug);
1580
+ return _createClass(Plugin, [{
1581
+ key: "init",
1582
+ value: function init() {
1583
+ var _defaultStyleRenderer;
1584
+ var canvasRendererPluginOptions = _objectSpread({
1585
+ dirtyObjectNumThreshold: 500,
1586
+ dirtyObjectRatioThreshold: 0.8
1587
+ }, this.options);
1588
+
1589
+ // @ts-ignore
1590
+ var imagePool = this.context.imagePool;
1591
+ var defaultRenderer = new DefaultRenderer(imagePool);
1592
+ var defaultStyleRendererFactory = (_defaultStyleRenderer = {}, _defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defaultStyleRenderer, Shape.CIRCLE, defaultRenderer), Shape.ELLIPSE, defaultRenderer), Shape.RECT, defaultRenderer), Shape.IMAGE, new ImageRenderer(imagePool)), Shape.TEXT, new TextRenderer(imagePool)), Shape.LINE, defaultRenderer), Shape.POLYLINE, defaultRenderer), Shape.POLYGON, defaultRenderer), Shape.PATH, defaultRenderer), Shape.GROUP, undefined), _defineProperty(_defineProperty(_defineProperty(_defaultStyleRenderer, Shape.HTML, undefined), Shape.MESH, undefined), Shape.FRAGMENT, undefined));
1593
+ this.context.defaultStyleRendererFactory = defaultStyleRendererFactory;
1594
+ this.context.styleRendererFactory = defaultStyleRendererFactory;
1595
+ this.addRenderingPlugin(new CanvasRendererPlugin(canvasRendererPluginOptions));
1596
+ }
1597
+ }, {
1598
+ key: "destroy",
1599
+ value: function destroy() {
1600
+ this.removeAllRenderingPlugins();
1601
+ delete this.context.defaultStyleRendererFactory;
1602
+ delete this.context.styleRendererFactory;
1603
+ }
1604
+ }]);
1605
+ }(AbstractRendererPlugin);
1606
+
1607
+ var index$2 = /*#__PURE__*/Object.freeze({
1608
+ __proto__: null,
1609
+ CircleRenderer: DefaultRenderer,
1610
+ DefaultRenderer: DefaultRenderer,
1611
+ EllipseRenderer: DefaultRenderer,
1612
+ ImageRenderer: ImageRenderer,
1613
+ LineRenderer: DefaultRenderer,
1614
+ PathRenderer: DefaultRenderer,
1615
+ Plugin: Plugin$2,
1616
+ PolygonRenderer: DefaultRenderer,
1617
+ PolylineRenderer: DefaultRenderer,
1618
+ RectRenderer: DefaultRenderer,
1619
+ TextRenderer: TextRenderer
1620
+ });
1621
+
1622
+ var tmpVec3a = vec3.create();
1623
+ var tmpVec3b = vec3.create();
1624
+ var tmpVec3c = vec3.create();
1625
+ var tmpMat4 = mat4.create();
1626
+ /**
1627
+ * pick shape(s) with Mouse/Touch event
1628
+ *
1629
+ * 1. find AABB with r-tree
1630
+ * 2. do math calculation with geometry in an accurate way
1631
+ */
1632
+ var CanvasPickerPlugin = /*#__PURE__*/function () {
1633
+ function CanvasPickerPlugin() {
1634
+ var _this = this;
1635
+ _classCallCheck(this, CanvasPickerPlugin);
1636
+ this.isHit = function (displayObject, position, worldTransform, isClipPath) {
1637
+ // use picker for current shape's type
1638
+ var pick = _this.context.pointInPathPickerFactory[displayObject.nodeName];
1639
+ if (pick) {
1640
+ // invert with world matrix
1641
+ var invertWorldMat = mat4.invert(tmpMat4, worldTransform);
1642
+
1643
+ // transform client position to local space, do picking in local space
1644
+ var localPosition = vec3.transformMat4(tmpVec3b, vec3.set(tmpVec3c, position[0], position[1], 0), invertWorldMat);
1645
+ if (pick(displayObject, new Point(localPosition[0], localPosition[1]), isClipPath, _this.isPointInPath, _this.context, _this.runtime)) {
1646
+ return true;
1647
+ }
1648
+ }
1649
+ return false;
1650
+ };
1651
+ /**
1652
+ * use native picking method
1653
+ * @see https://developer.mozilla.org/zh-CN/docs/Web/API/CanvasRenderingContext2D/isPointInPath
1654
+ */
1655
+ this.isPointInPath = function (displayObject, position) {
1656
+ var context = _this.runtime.offscreenCanvasCreator.getOrCreateContext(_this.context.config.offscreenCanvas);
1657
+ var generatePath = _this.context.pathGeneratorFactory[displayObject.nodeName];
1658
+ if (generatePath) {
1659
+ context.beginPath();
1660
+ generatePath(context, displayObject.parsedStyle);
1661
+ context.closePath();
1662
+ }
1663
+ return context.isPointInPath(position.x, position.y);
1664
+ };
1665
+ }
1666
+ return _createClass(CanvasPickerPlugin, [{
1667
+ key: "apply",
1668
+ value: function apply(context, runtime) {
1669
+ var _renderingContext$roo,
1670
+ _this2 = this;
1671
+ var renderingService = context.renderingService,
1672
+ renderingContext = context.renderingContext;
1673
+ this.context = context;
1674
+ this.runtime = runtime;
1675
+ var document = (_renderingContext$roo = renderingContext.root) === null || _renderingContext$roo === void 0 ? void 0 : _renderingContext$roo.ownerDocument;
1676
+ renderingService.hooks.pick.tapPromise(CanvasPickerPlugin.tag, /*#__PURE__*/function () {
1677
+ var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(result) {
1678
+ return _regeneratorRuntime().wrap(function (_context) {
1679
+ while (1) switch (_context.prev = _context.next) {
1680
+ case 0:
1681
+ return _context.abrupt("return", _this2.pick(document, result));
1682
+ case 1:
1683
+ case "end":
1684
+ return _context.stop();
1685
+ }
1686
+ }, _callee);
1687
+ }));
1688
+ return function (_x) {
1689
+ return _ref.apply(this, arguments);
1690
+ };
1691
+ }());
1692
+ renderingService.hooks.pickSync.tap(CanvasPickerPlugin.tag, function (result) {
1693
+ return _this2.pick(document, result);
1694
+ });
1695
+ }
1696
+ }, {
1697
+ key: "pick",
1698
+ value: function pick(document, result) {
1699
+ var topmost = result.topmost,
1700
+ _result$position = result.position,
1701
+ x = _result$position.x,
1702
+ y = _result$position.y;
1703
+
1704
+ // position in world space
1705
+ var position = vec3.set(tmpVec3a, x, y, 0);
1706
+
1707
+ // query by AABB
1708
+ var hitTestList = document.elementsFromBBox(position[0], position[1], position[0], position[1]);
1709
+
1710
+ // test with clip path & origin shape
1711
+ // @see https://github.com/antvis/g/issues/1064
1712
+ var pickedDisplayObjects = [];
1713
+ var _iterator = _createForOfIteratorHelper(hitTestList),
1714
+ _step;
1715
+ try {
1716
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
1717
+ var _displayObject = _step.value;
1718
+ var worldTransform = _displayObject.getWorldTransform();
1719
+ var isHitOriginShape = this.isHit(_displayObject, position, worldTransform, false);
1720
+ if (isHitOriginShape) {
1721
+ // should look up in the ancestor node
1722
+ var clipped = findClosestClipPathTarget(_displayObject);
1723
+ if (clipped) {
1724
+ var clipPath = clipped.parsedStyle.clipPath;
1725
+ var isHitClipPath = this.isHit(clipPath, position, clipPath.getWorldTransform(), true);
1726
+ if (isHitClipPath) {
1727
+ if (topmost) {
1728
+ result.picked = [_displayObject];
1729
+ return result;
1730
+ }
1731
+ pickedDisplayObjects.push(_displayObject);
1732
+ }
1733
+ } else {
1734
+ if (topmost) {
1735
+ result.picked = [_displayObject];
1736
+ return result;
1737
+ }
1738
+ pickedDisplayObjects.push(_displayObject);
1739
+ }
1740
+ }
1741
+ }
1742
+ } catch (err) {
1743
+ _iterator.e(err);
1744
+ } finally {
1745
+ _iterator.f();
1746
+ }
1747
+ result.picked = pickedDisplayObjects;
1748
+ return result;
1749
+ }
1750
+ }]);
1751
+ }();
1752
+ CanvasPickerPlugin.tag = 'CanvasPicker';
1753
+
1754
+ function isPointInPath$8(displayObject, position, isClipPath) {
1755
+ var _ref = displayObject.parsedStyle,
1756
+ _ref$cx = _ref.cx,
1757
+ cx = _ref$cx === void 0 ? 0 : _ref$cx,
1758
+ _ref$cy = _ref.cy,
1759
+ cy = _ref$cy === void 0 ? 0 : _ref$cy,
1760
+ r = _ref.r,
1761
+ fill = _ref.fill,
1762
+ stroke = _ref.stroke,
1763
+ _ref$lineWidth = _ref.lineWidth,
1764
+ lineWidth = _ref$lineWidth === void 0 ? 1 : _ref$lineWidth,
1765
+ _ref$increasedLineWid = _ref.increasedLineWidthForHitTesting,
1766
+ increasedLineWidthForHitTesting = _ref$increasedLineWid === void 0 ? 0 : _ref$increasedLineWid,
1767
+ _ref$pointerEvents = _ref.pointerEvents,
1768
+ pointerEvents = _ref$pointerEvents === void 0 ? 'auto' : _ref$pointerEvents;
1769
+ var halfLineWidth = (lineWidth + increasedLineWidthForHitTesting) / 2;
1770
+ var absDistance = distance(cx, cy, position.x, position.y);
1771
+ var _isFillOrStrokeAffect = isFillOrStrokeAffected(pointerEvents, fill, stroke),
1772
+ _isFillOrStrokeAffect2 = _slicedToArray(_isFillOrStrokeAffect, 2),
1773
+ hasFill = _isFillOrStrokeAffect2[0],
1774
+ hasStroke = _isFillOrStrokeAffect2[1];
1775
+ if (hasFill && hasStroke || isClipPath) {
1776
+ return absDistance <= r + halfLineWidth;
1777
+ }
1778
+ if (hasFill) {
1779
+ return absDistance <= r;
1780
+ }
1781
+ if (hasStroke) {
1782
+ return absDistance >= r - halfLineWidth && absDistance <= r + halfLineWidth;
1783
+ }
1784
+ return false;
1785
+ }
1786
+
1787
+ function ellipseDistance(squareX, squareY, rx, ry) {
1788
+ return squareX / (rx * rx) + squareY / (ry * ry);
1789
+ }
1790
+ function isPointInPath$7(displayObject, position, isClipPath) {
1791
+ var _ref = displayObject.parsedStyle,
1792
+ _ref$cx = _ref.cx,
1793
+ cx = _ref$cx === void 0 ? 0 : _ref$cx,
1794
+ _ref$cy = _ref.cy,
1795
+ cy = _ref$cy === void 0 ? 0 : _ref$cy,
1796
+ rx = _ref.rx,
1797
+ ry = _ref.ry,
1798
+ fill = _ref.fill,
1799
+ stroke = _ref.stroke,
1800
+ _ref$lineWidth = _ref.lineWidth,
1801
+ lineWidth = _ref$lineWidth === void 0 ? 1 : _ref$lineWidth,
1802
+ _ref$increasedLineWid = _ref.increasedLineWidthForHitTesting,
1803
+ increasedLineWidthForHitTesting = _ref$increasedLineWid === void 0 ? 0 : _ref$increasedLineWid,
1804
+ _ref$pointerEvents = _ref.pointerEvents,
1805
+ pointerEvents = _ref$pointerEvents === void 0 ? 'auto' : _ref$pointerEvents;
1806
+ var x = position.x,
1807
+ y = position.y;
1808
+ var _isFillOrStrokeAffect = isFillOrStrokeAffected(pointerEvents, fill, stroke),
1809
+ _isFillOrStrokeAffect2 = _slicedToArray(_isFillOrStrokeAffect, 2),
1810
+ hasFill = _isFillOrStrokeAffect2[0],
1811
+ hasStroke = _isFillOrStrokeAffect2[1];
1812
+ var halfLineWith = (lineWidth + increasedLineWidthForHitTesting) / 2;
1813
+ var squareX = (x - cx) * (x - cx);
1814
+ var squareY = (y - cy) * (y - cy);
1815
+ // 使用椭圆的公式: x*x/rx*rx + y*y/ry*ry = 1;
1816
+ if (hasFill && hasStroke || isClipPath) {
1817
+ return ellipseDistance(squareX, squareY, rx + halfLineWith, ry + halfLineWith) <= 1;
1818
+ }
1819
+ if (hasFill) {
1820
+ return ellipseDistance(squareX, squareY, rx, ry) <= 1;
1821
+ }
1822
+ if (hasStroke) {
1823
+ return ellipseDistance(squareX, squareY, rx - halfLineWith, ry - halfLineWith) >= 1 && ellipseDistance(squareX, squareY, rx + halfLineWith, ry + halfLineWith) <= 1;
1824
+ }
1825
+ return false;
1826
+ }
1827
+
1828
+ function inBox(minX, minY, width, height, x, y) {
1829
+ return x >= minX && x <= minX + width && y >= minY && y <= minY + height;
1830
+ }
1831
+ function inRect(minX, minY, width, height, lineWidth, x, y) {
1832
+ var halfWidth = lineWidth / 2;
1833
+ // 将四个边看做矩形来检测,比边的检测算法要快
1834
+ return inBox(minX - halfWidth, minY - halfWidth, width, lineWidth, x, y) ||
1835
+ // 上边
1836
+ inBox(minX + width - halfWidth, minY - halfWidth, lineWidth, height, x, y) ||
1837
+ // 右边
1838
+ inBox(minX + halfWidth, minY + height - halfWidth, width, lineWidth, x, y) ||
1839
+ // 下边
1840
+ inBox(minX - halfWidth, minY + halfWidth, lineWidth, height, x, y); // 左边
1841
+ }
1842
+ function inArc(cx, cy, r, startAngle, endAngle, lineWidth, x, y) {
1843
+ var angle = (Math.atan2(y - cy, x - cx) + Math.PI * 2) % (Math.PI * 2); // 转换到 0 - 2 * Math.PI 之间
1844
+ // if (angle < startAngle || angle > endAngle) {
1845
+ // return false;
1846
+ // }
1847
+ var point = {
1848
+ x: cx + r * Math.cos(angle),
1849
+ y: cy + r * Math.sin(angle)
1850
+ };
1851
+ return distance(point.x, point.y, x, y) <= lineWidth / 2;
1852
+ }
1853
+ function inLine(x1, y1, x2, y2, lineWidth, x, y) {
1854
+ var minX = Math.min(x1, x2);
1855
+ var maxX = Math.max(x1, x2);
1856
+ var minY = Math.min(y1, y2);
1857
+ var maxY = Math.max(y1, y2);
1858
+ var halfWidth = lineWidth / 2;
1859
+ // 因为目前的方案是计算点到直线的距离,而有可能会在延长线上,所以要先判断是否在包围盒内
1860
+ // 这种方案会在水平或者竖直的情况下载线的延长线上有半 lineWidth 的误差
1861
+ if (!(x >= minX - halfWidth && x <= maxX + halfWidth && y >= minY - halfWidth && y <= maxY + halfWidth)) {
1862
+ return false;
1863
+ }
1864
+ // 因为已经计算了包围盒,所以仅需要计算到直线的距离即可,可以显著提升性能
1865
+ return linePointToLine(x1, y1, x2, y2, x, y) <= lineWidth / 2;
1866
+ }
1867
+ function inPolyline(points, lineWidth, x, y, isClose) {
1868
+ var count = points.length;
1869
+ if (count < 2) {
1870
+ return false;
1871
+ }
1872
+ for (var i = 0; i < count - 1; i++) {
1873
+ var x1 = points[i][0];
1874
+ var y1 = points[i][1];
1875
+ var x2 = points[i + 1][0];
1876
+ var y2 = points[i + 1][1];
1877
+ if (inLine(x1, y1, x2, y2, lineWidth, x, y)) {
1878
+ return true;
1879
+ }
1880
+ }
1881
+
1882
+ // 如果封闭,则计算起始点和结束点的边
1883
+ if (isClose) {
1884
+ var first = points[0];
1885
+ var last = points[count - 1];
1886
+ if (inLine(first[0], first[1], last[0], last[1], lineWidth, x, y)) {
1887
+ return true;
1888
+ }
1889
+ }
1890
+ return false;
1891
+ }
1892
+
1893
+ // 多边形的射线检测,参考:https://blog.csdn.net/WilliamSun0122/article/details/77994526
1894
+ var tolerance = 1e-6;
1895
+ // 三态函数,判断两个double在eps精度下的大小关系
1896
+ function dcmp(x) {
1897
+ if (Math.abs(x) < tolerance) {
1898
+ return 0;
1899
+ }
1900
+ return x < 0 ? -1 : 1;
1901
+ }
1902
+
1903
+ // 判断点Q是否在p1和p2的线段上
1904
+ function onSegment(p1, p2, q) {
1905
+ if ((q[0] - p1[0]) * (p2[1] - p1[1]) === (p2[0] - p1[0]) * (q[1] - p1[1]) && Math.min(p1[0], p2[0]) <= q[0] && q[0] <= Math.max(p1[0], p2[0]) && Math.min(p1[1], p2[1]) <= q[1] && q[1] <= Math.max(p1[1], p2[1])) {
1906
+ return true;
1907
+ }
1908
+ return false;
1909
+ }
1910
+
1911
+ // 判断点P在多边形内-射线法
1912
+ function inPolygon(points, x, y) {
1913
+ var isHit = false;
1914
+ var n = points.length;
1915
+ if (n <= 2) {
1916
+ // svg 中点小于 3 个时,不显示,也无法被拾取
1917
+ return false;
1918
+ }
1919
+ for (var i = 0; i < n; i++) {
1920
+ var p1 = points[i];
1921
+ var p2 = points[(i + 1) % n];
1922
+ if (onSegment(p1, p2, [x, y])) {
1923
+ // 点在多边形一条边上
1924
+ return true;
1925
+ }
1926
+ // 前一个判断min(p1[1],p2[1])<P.y<=max(p1[1],p2[1])
1927
+ // 后一个判断被测点 在 射线与边交点 的左边
1928
+ if (dcmp(p1[1] - y) > 0 !== dcmp(p2[1] - y) > 0 && dcmp(x - (y - p1[1]) * (p1[0] - p2[0]) / (p1[1] - p2[1]) - p1[0]) < 0) {
1929
+ isHit = !isHit;
1930
+ }
1931
+ }
1932
+ return isHit;
1933
+ }
1934
+ function inPolygons(polygons, x, y) {
1935
+ var isHit = false;
1936
+ for (var i = 0; i < polygons.length; i++) {
1937
+ var points = polygons[i];
1938
+ isHit = inPolygon(points, x, y);
1939
+ if (isHit) {
1940
+ break;
1941
+ }
1942
+ }
1943
+ return isHit;
1944
+ }
1945
+
1946
+ function isPointInPath$6(displayObject, position, isClipPath) {
1947
+ var _ref = displayObject.parsedStyle,
1948
+ x1 = _ref.x1,
1949
+ y1 = _ref.y1,
1950
+ x2 = _ref.x2,
1951
+ y2 = _ref.y2,
1952
+ _ref$lineWidth = _ref.lineWidth,
1953
+ lineWidth = _ref$lineWidth === void 0 ? 1 : _ref$lineWidth,
1954
+ _ref$increasedLineWid = _ref.increasedLineWidthForHitTesting,
1955
+ increasedLineWidthForHitTesting = _ref$increasedLineWid === void 0 ? 0 : _ref$increasedLineWid,
1956
+ _ref$pointerEvents = _ref.pointerEvents,
1957
+ pointerEvents = _ref$pointerEvents === void 0 ? 'auto' : _ref$pointerEvents,
1958
+ fill = _ref.fill,
1959
+ stroke = _ref.stroke;
1960
+ var _isFillOrStrokeAffect = isFillOrStrokeAffected(pointerEvents, fill, stroke),
1961
+ _isFillOrStrokeAffect2 = _slicedToArray(_isFillOrStrokeAffect, 2),
1962
+ hasStroke = _isFillOrStrokeAffect2[1];
1963
+ if (!hasStroke && !isClipPath || !lineWidth) {
1964
+ return false;
1965
+ }
1966
+ return inLine(x1, y1, x2, y2, lineWidth + increasedLineWidthForHitTesting, position.x, position.y);
1967
+ }
1968
+
1969
+ // TODO: replace it with method in @antv/util
1970
+ function isPointInStroke(segments, lineWidth, px, py, length) {
1971
+ var isHit = false;
1972
+ var halfWidth = lineWidth / 2;
1973
+ for (var i = 0; i < segments.length; i++) {
1974
+ var segment = segments[i];
1975
+ var currentPoint = segment.currentPoint,
1976
+ params = segment.params,
1977
+ prePoint = segment.prePoint,
1978
+ box = segment.box;
1979
+ // 如果在前面已经生成过包围盒,直接按照包围盒计算
1980
+ if (box && !inBox(box.x - halfWidth, box.y - halfWidth, box.width + lineWidth, box.height + lineWidth, px, py)) {
1981
+ continue;
1982
+ }
1983
+ switch (segment.command) {
1984
+ // L 和 Z 都是直线, M 不进行拾取
1985
+ case 'L':
1986
+ case 'Z':
1987
+ isHit = inLine(prePoint[0], prePoint[1], currentPoint[0], currentPoint[1], lineWidth, px, py);
1988
+ if (isHit) {
1989
+ return true;
1990
+ }
1991
+ break;
1992
+ case 'Q':
1993
+ var qDistance = quadPointDistance(prePoint[0], prePoint[1], params[1], params[2], params[3], params[4], px, py);
1994
+ isHit = qDistance <= lineWidth / 2;
1995
+ if (isHit) {
1996
+ return true;
1997
+ }
1998
+ break;
1999
+ case 'C':
2000
+ var cDistance = cubicPointDistance(prePoint[0],
2001
+ // 上一段结束位置, 即 C 的起始点
2002
+ prePoint[1], params[1],
2003
+ // 'C' 的参数,1、2 为第一个控制点,3、4 为第二个控制点,5、6 为结束点
2004
+ params[2], params[3], params[4], params[5], params[6], px, py, length);
2005
+ isHit = cDistance <= lineWidth / 2;
2006
+ if (isHit) {
2007
+ return true;
2008
+ }
2009
+ break;
2010
+ case 'A':
2011
+ // cache conversion result
2012
+ if (!segment.cubicParams) {
2013
+ segment.cubicParams = arcToCubic(prePoint[0], prePoint[1], params[1], params[2], params[3], params[4], params[5], params[6], params[7], undefined);
2014
+ }
2015
+ var args = segment.cubicParams;
2016
+
2017
+ // fixArc
2018
+ var prePointInCubic = prePoint;
2019
+ for (var _i = 0; _i < args.length; _i += 6) {
2020
+ var _cDistance = cubicPointDistance(prePointInCubic[0],
2021
+ // 上一段结束位置, 即 C 的起始点
2022
+ prePointInCubic[1], args[_i], args[_i + 1], args[_i + 2], args[_i + 3], args[_i + 4], args[_i + 5], px, py, length);
2023
+ prePointInCubic = [args[_i + 4], args[_i + 5]];
2024
+ isHit = _cDistance <= lineWidth / 2;
2025
+ if (isHit) {
2026
+ return true;
2027
+ }
2028
+ }
2029
+ break;
2030
+ }
2031
+ }
2032
+ return isHit;
2033
+ }
2034
+ function isPointInPath$5(displayObject, position, isClipPath, isPointInPath, renderingPluginContext, runtime) {
2035
+ var _ref = displayObject.parsedStyle,
2036
+ _ref$lineWidth = _ref.lineWidth,
2037
+ lineWidth = _ref$lineWidth === void 0 ? 1 : _ref$lineWidth,
2038
+ _ref$increasedLineWid = _ref.increasedLineWidthForHitTesting,
2039
+ increasedLineWidthForHitTesting = _ref$increasedLineWid === void 0 ? 0 : _ref$increasedLineWid,
2040
+ stroke = _ref.stroke,
2041
+ fill = _ref.fill,
2042
+ d = _ref.d,
2043
+ _ref$pointerEvents = _ref.pointerEvents,
2044
+ pointerEvents = _ref$pointerEvents === void 0 ? 'auto' : _ref$pointerEvents;
2045
+ var segments = d.segments,
2046
+ hasArc = d.hasArc,
2047
+ polylines = d.polylines,
2048
+ polygons = d.polygons;
2049
+ var _isFillOrStrokeAffect = isFillOrStrokeAffected(pointerEvents,
2050
+ // Only a closed path can be filled.
2051
+ (polygons === null || polygons === void 0 ? void 0 : polygons.length) && fill, stroke),
2052
+ _isFillOrStrokeAffect2 = _slicedToArray(_isFillOrStrokeAffect, 2),
2053
+ hasFill = _isFillOrStrokeAffect2[0],
2054
+ hasStroke = _isFillOrStrokeAffect2[1];
2055
+ var totalLength = getOrCalculatePathTotalLength(displayObject);
2056
+ var isHit = false;
2057
+ if (hasFill || isClipPath) {
2058
+ if (hasArc) {
2059
+ // 存在曲线时,暂时使用 canvas 的 api 计算,后续可以进行多边形切割
2060
+ isHit = isPointInPath(displayObject, position);
2061
+ } else {
2062
+ // 提取出来的多边形包含闭合的和非闭合的,在这里统一按照多边形处理
2063
+ isHit = inPolygons(polygons, position.x, position.y) || inPolygons(polylines, position.x, position.y);
2064
+ }
2065
+ return isHit;
2066
+ }
2067
+ if (hasStroke || isClipPath) {
2068
+ isHit = isPointInStroke(segments, lineWidth + increasedLineWidthForHitTesting, position.x, position.y, totalLength);
2069
+ }
2070
+ return isHit;
2071
+ }
2072
+
2073
+ function isPointInPath$4(displayObject, position, isClipPath) {
2074
+ var _ref = displayObject.parsedStyle,
2075
+ stroke = _ref.stroke,
2076
+ fill = _ref.fill,
2077
+ _ref$lineWidth = _ref.lineWidth,
2078
+ lineWidth = _ref$lineWidth === void 0 ? 1 : _ref$lineWidth,
2079
+ _ref$increasedLineWid = _ref.increasedLineWidthForHitTesting,
2080
+ increasedLineWidthForHitTesting = _ref$increasedLineWid === void 0 ? 0 : _ref$increasedLineWid,
2081
+ points = _ref.points,
2082
+ _ref$pointerEvents = _ref.pointerEvents,
2083
+ pointerEvents = _ref$pointerEvents === void 0 ? 'auto' : _ref$pointerEvents;
2084
+ var _isFillOrStrokeAffect = isFillOrStrokeAffected(pointerEvents, fill, stroke),
2085
+ _isFillOrStrokeAffect2 = _slicedToArray(_isFillOrStrokeAffect, 2),
2086
+ hasFill = _isFillOrStrokeAffect2[0],
2087
+ hasStroke = _isFillOrStrokeAffect2[1];
2088
+ var isHit = false;
2089
+ if (hasStroke || isClipPath) {
2090
+ isHit = inPolyline(points.points, lineWidth + increasedLineWidthForHitTesting, position.x, position.y, true);
2091
+ }
2092
+ if (!isHit && (hasFill || isClipPath)) {
2093
+ isHit = inPolygon(points.points, position.x, position.y);
2094
+ }
2095
+ return isHit;
2096
+ }
2097
+
2098
+ function isPointInPath$3(displayObject, position, isClipPath) {
2099
+ var _ref = displayObject.parsedStyle,
2100
+ _ref$lineWidth = _ref.lineWidth,
2101
+ lineWidth = _ref$lineWidth === void 0 ? 1 : _ref$lineWidth,
2102
+ _ref$increasedLineWid = _ref.increasedLineWidthForHitTesting,
2103
+ increasedLineWidthForHitTesting = _ref$increasedLineWid === void 0 ? 0 : _ref$increasedLineWid,
2104
+ points = _ref.points,
2105
+ _ref$pointerEvents = _ref.pointerEvents,
2106
+ pointerEvents = _ref$pointerEvents === void 0 ? 'auto' : _ref$pointerEvents,
2107
+ fill = _ref.fill,
2108
+ stroke = _ref.stroke;
2109
+ var _isFillOrStrokeAffect = isFillOrStrokeAffected(pointerEvents, fill, stroke),
2110
+ _isFillOrStrokeAffect2 = _slicedToArray(_isFillOrStrokeAffect, 2),
2111
+ hasStroke = _isFillOrStrokeAffect2[1];
2112
+ if (!hasStroke && !isClipPath || !lineWidth) {
2113
+ return false;
2114
+ }
2115
+ return inPolyline(points.points, lineWidth + increasedLineWidthForHitTesting, position.x, position.y, false);
2116
+ }
2117
+
2118
+ function isPointInPath$2(displayObject, position, isClipPath, isPointInPath, runtime) {
2119
+ var _ref = displayObject.parsedStyle,
2120
+ radius = _ref.radius,
2121
+ fill = _ref.fill,
2122
+ stroke = _ref.stroke,
2123
+ _ref$lineWidth = _ref.lineWidth,
2124
+ lineWidth = _ref$lineWidth === void 0 ? 1 : _ref$lineWidth,
2125
+ _ref$increasedLineWid = _ref.increasedLineWidthForHitTesting,
2126
+ increasedLineWidthForHitTesting = _ref$increasedLineWid === void 0 ? 0 : _ref$increasedLineWid,
2127
+ _ref$x = _ref.x,
2128
+ x = _ref$x === void 0 ? 0 : _ref$x,
2129
+ _ref$y = _ref.y,
2130
+ y = _ref$y === void 0 ? 0 : _ref$y,
2131
+ width = _ref.width,
2132
+ height = _ref.height,
2133
+ _ref$pointerEvents = _ref.pointerEvents,
2134
+ pointerEvents = _ref$pointerEvents === void 0 ? 'auto' : _ref$pointerEvents;
2135
+ var _isFillOrStrokeAffect = isFillOrStrokeAffected(pointerEvents, fill, stroke),
2136
+ _isFillOrStrokeAffect2 = _slicedToArray(_isFillOrStrokeAffect, 2),
2137
+ hasFill = _isFillOrStrokeAffect2[0],
2138
+ hasStroke = _isFillOrStrokeAffect2[1];
2139
+ var hasRadius = radius && radius.some(function (r) {
2140
+ return r !== 0;
2141
+ });
2142
+ var lineWidthForHitTesting = lineWidth + increasedLineWidthForHitTesting;
2143
+
2144
+ // 无圆角时的策略
2145
+ if (!hasRadius) {
2146
+ var halfWidth = lineWidthForHitTesting / 2;
2147
+ // 同时填充和带有边框
2148
+ if (hasFill && hasStroke || isClipPath) {
2149
+ return inBox(x - halfWidth, y - halfWidth, width + halfWidth, height + halfWidth, position.x, position.y);
2150
+ }
2151
+ // 仅填充
2152
+ if (hasFill) {
2153
+ return inBox(x, y, width, height, position.x, position.y);
2154
+ }
2155
+ if (hasStroke) {
2156
+ return inRect(x, y, width, height, lineWidthForHitTesting, position.x, position.y);
2157
+ }
2158
+ } else {
2159
+ var isHit = false;
2160
+ if (hasStroke || isClipPath) {
2161
+ isHit = inRectWithRadius(x, y, width, height, radius.map(function (r) {
2162
+ return clamp(r, 0, Math.min(Math.abs(width) / 2, Math.abs(height) / 2));
2163
+ }), lineWidthForHitTesting, position.x, position.y);
2164
+ }
2165
+ // 仅填充时带有圆角的矩形直接通过图形拾取
2166
+ // 以后可以改成纯数学的近似拾取,将圆弧切割成多边形
2167
+ if (!isHit && (hasFill || isClipPath)) {
2168
+ isHit = isPointInPath(displayObject, position);
2169
+ }
2170
+ return isHit;
2171
+ }
2172
+ return false;
2173
+ }
2174
+ function inRectWithRadius(minX, minY, width, height, radiusArray, lineWidth, x, y) {
2175
+ var _radiusArray = _slicedToArray(radiusArray, 4),
2176
+ tlr = _radiusArray[0],
2177
+ trr = _radiusArray[1],
2178
+ brr = _radiusArray[2],
2179
+ blr = _radiusArray[3];
2180
+ return inLine(minX + tlr, minY, minX + width - trr, minY, lineWidth, x, y) || inLine(minX + width, minY + trr, minX + width, minY + height - brr, lineWidth, x, y) || inLine(minX + width - brr, minY + height, minX + blr, minY + height, lineWidth, x, y) || inLine(minX, minY + height - blr, minX, minY + tlr, lineWidth, x, y) || inArc(minX + width - trr, minY + trr, trr, 1.5 * Math.PI, 2 * Math.PI, lineWidth, x, y) || inArc(minX + width - brr, minY + height - brr, brr, 0, 0.5 * Math.PI, lineWidth, x, y) || inArc(minX + blr, minY + height - blr, blr, 0.5 * Math.PI, Math.PI, lineWidth, x, y) || inArc(minX + tlr, minY + tlr, tlr, Math.PI, 1.5 * Math.PI, lineWidth, x, y);
2181
+ }
2182
+
2183
+ function isPointInPath$1(displayObject, position, isClipPath, isPointInPath, renderingPluginContext, runtime) {
2184
+ var _ref = displayObject.parsedStyle,
2185
+ _ref$pointerEvents = _ref.pointerEvents,
2186
+ pointerEvents = _ref$pointerEvents === void 0 ? 'auto' : _ref$pointerEvents,
2187
+ _ref$x = _ref.x,
2188
+ x = _ref$x === void 0 ? 0 : _ref$x,
2189
+ _ref$y = _ref.y,
2190
+ y = _ref$y === void 0 ? 0 : _ref$y,
2191
+ width = _ref.width,
2192
+ height = _ref.height;
2193
+ if (pointerEvents === 'non-transparent-pixel') {
2194
+ var offscreenCanvas = renderingPluginContext.config.offscreenCanvas;
2195
+ var canvas = runtime.offscreenCanvasCreator.getOrCreateCanvas(offscreenCanvas);
2196
+ var context = runtime.offscreenCanvasCreator.getOrCreateContext(offscreenCanvas, {
2197
+ willReadFrequently: true
2198
+ });
2199
+ canvas.width = width;
2200
+ canvas.height = height;
2201
+ renderingPluginContext.defaultStyleRendererFactory[Shape.IMAGE].render(context, _objectSpread(_objectSpread({}, displayObject.parsedStyle), {}, {
2202
+ x: 0,
2203
+ y: 0
2204
+ }), displayObject, undefined, undefined, undefined);
2205
+ var imagedata = context.getImageData(position.x - x, position.y - y, 1, 1).data;
2206
+ return imagedata.every(function (component) {
2207
+ return component !== 0;
2208
+ });
2209
+ }
2210
+ return true;
2211
+ }
2212
+
2213
+ function isPointInPath(displayObject, position, isClipPath, isPointInPath) {
2214
+ var bounds = displayObject.getGeometryBounds();
2215
+
2216
+ // @see https://stackoverflow.com/questions/28706989/how-do-i-check-if-a-mouse-click-is-inside-a-rotated-text-on-the-html5-canvas-in
2217
+ return position.x >= bounds.min[0] && position.y >= bounds.min[1] && position.x <= bounds.max[0] && position.y <= bounds.max[1];
2218
+ }
2219
+
2220
+ var Plugin$1 = /*#__PURE__*/function (_AbstractRendererPlug) {
2221
+ function Plugin() {
2222
+ var _this;
2223
+ _classCallCheck(this, Plugin);
2224
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
2225
+ args[_key] = arguments[_key];
2226
+ }
2227
+ _this = _callSuper(this, Plugin, [].concat(args));
2228
+ _this.name = 'canvas-picker';
2229
+ return _this;
2230
+ }
2231
+ _inherits(Plugin, _AbstractRendererPlug);
2232
+ return _createClass(Plugin, [{
2233
+ key: "init",
2234
+ value: function init() {
2235
+ var _pointInPathPickerFac;
2236
+ var pointInPathPickerFactory = (_pointInPathPickerFac = {}, _defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_pointInPathPickerFac, Shape.CIRCLE, isPointInPath$8), Shape.ELLIPSE, isPointInPath$7), Shape.RECT, isPointInPath$2), Shape.LINE, isPointInPath$6), Shape.POLYLINE, isPointInPath$3), Shape.POLYGON, isPointInPath$4), Shape.PATH, isPointInPath$5), Shape.TEXT, isPointInPath), Shape.GROUP, null), Shape.IMAGE, isPointInPath$1), _defineProperty(_defineProperty(_pointInPathPickerFac, Shape.HTML, null), Shape.MESH, null));
2237
+
2238
+ // @ts-ignore
2239
+ this.context.pointInPathPickerFactory = pointInPathPickerFactory;
2240
+ this.addRenderingPlugin(new CanvasPickerPlugin());
2241
+ }
2242
+ }, {
2243
+ key: "destroy",
2244
+ value: function destroy() {
2245
+ // @ts-ignore
2246
+ delete this.context.pointInPathPickerFactory;
2247
+ this.removeAllRenderingPlugins();
2248
+ }
2249
+ }]);
2250
+ }(AbstractRendererPlugin);
2251
+
2252
+ var index$1 = /*#__PURE__*/Object.freeze({
2253
+ __proto__: null,
2254
+ Plugin: Plugin$1
2255
+ });
2256
+
2257
+ function generatePath$6(context, parsedStyle) {
2258
+ var _parsedStyle$cx = parsedStyle.cx,
2259
+ cx = _parsedStyle$cx === void 0 ? 0 : _parsedStyle$cx,
2260
+ _parsedStyle$cy = parsedStyle.cy,
2261
+ cy = _parsedStyle$cy === void 0 ? 0 : _parsedStyle$cy,
2262
+ r = parsedStyle.r;
2263
+ context.arc(cx, cy, r, 0, Math.PI * 2, false);
2264
+ }
2265
+
2266
+ function generatePath$5(context, parsedStyle) {
2267
+ var _parsedStyle$cx = parsedStyle.cx,
2268
+ cx = _parsedStyle$cx === void 0 ? 0 : _parsedStyle$cx,
2269
+ _parsedStyle$cy = parsedStyle.cy,
2270
+ cy = _parsedStyle$cy === void 0 ? 0 : _parsedStyle$cy,
2271
+ rx = parsedStyle.rx,
2272
+ ry = parsedStyle.ry;
2273
+
2274
+ // @see https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/ellipse
2275
+ if (context.ellipse) {
2276
+ context.ellipse(cx, cy, rx, ry, 0, 0, Math.PI * 2, false);
2277
+ } else {
2278
+ // 如果不支持,则使用圆来绘制,进行变形
2279
+ var r = rx > ry ? rx : ry;
2280
+ var scaleX = rx > ry ? 1 : rx / ry;
2281
+ var scaleY = rx > ry ? ry / rx : 1;
2282
+ context.save();
2283
+ context.scale(scaleX, scaleY);
2284
+ context.arc(cx, cy, r, 0, Math.PI * 2);
2285
+ }
2286
+ }
2287
+
2288
+ function generatePath$4(context, parsedStyle) {
2289
+ var x1 = parsedStyle.x1,
2290
+ y1 = parsedStyle.y1,
2291
+ x2 = parsedStyle.x2,
2292
+ y2 = parsedStyle.y2,
2293
+ markerStart = parsedStyle.markerStart,
2294
+ markerEnd = parsedStyle.markerEnd,
2295
+ markerStartOffset = parsedStyle.markerStartOffset,
2296
+ markerEndOffset = parsedStyle.markerEndOffset;
2297
+ var startOffsetX = 0;
2298
+ var startOffsetY = 0;
2299
+ var endOffsetX = 0;
2300
+ var endOffsetY = 0;
2301
+ var rad = 0;
2302
+ var x;
2303
+ var y;
2304
+ if (markerStart && isDisplayObject(markerStart) && markerStartOffset) {
2305
+ x = x2 - x1;
2306
+ y = y2 - y1;
2307
+ rad = Math.atan2(y, x);
2308
+ startOffsetX = Math.cos(rad) * (markerStartOffset || 0);
2309
+ startOffsetY = Math.sin(rad) * (markerStartOffset || 0);
2310
+ }
2311
+ if (markerEnd && isDisplayObject(markerEnd) && markerEndOffset) {
2312
+ x = x1 - x2;
2313
+ y = y1 - y2;
2314
+ rad = Math.atan2(y, x);
2315
+ endOffsetX = Math.cos(rad) * (markerEndOffset || 0);
2316
+ endOffsetY = Math.sin(rad) * (markerEndOffset || 0);
2317
+ }
2318
+ context.moveTo(x1 + startOffsetX, y1 + startOffsetY);
2319
+ context.lineTo(x2 + endOffsetX, y2 + endOffsetY);
2320
+ }
2321
+
2322
+ function generatePath$3(context, parsedStyle) {
2323
+ var markerStart = parsedStyle.markerStart,
2324
+ markerEnd = parsedStyle.markerEnd,
2325
+ markerStartOffset = parsedStyle.markerStartOffset,
2326
+ markerEndOffset = parsedStyle.markerEndOffset;
2327
+ var _parsedStyle$d = parsedStyle.d,
2328
+ absolutePath = _parsedStyle$d.absolutePath,
2329
+ segments = _parsedStyle$d.segments;
2330
+ var startOffsetX = 0;
2331
+ var startOffsetY = 0;
2332
+ var endOffsetX = 0;
2333
+ var endOffsetY = 0;
2334
+ var rad = 0;
2335
+ var x;
2336
+ var y;
2337
+ if (markerStart && isDisplayObject(markerStart) && markerStartOffset) {
2338
+ var _getStartTangent = markerStart.parentNode.getStartTangent(),
2339
+ _getStartTangent2 = _slicedToArray(_getStartTangent, 2),
2340
+ p1 = _getStartTangent2[0],
2341
+ p2 = _getStartTangent2[1];
2342
+ x = p1[0] - p2[0];
2343
+ y = p1[1] - p2[1];
2344
+ rad = Math.atan2(y, x);
2345
+ startOffsetX = Math.cos(rad) * (markerStartOffset || 0);
2346
+ startOffsetY = Math.sin(rad) * (markerStartOffset || 0);
2347
+ }
2348
+ if (markerEnd && isDisplayObject(markerEnd) && markerEndOffset) {
2349
+ var _getEndTangent = markerEnd.parentNode.getEndTangent(),
2350
+ _getEndTangent2 = _slicedToArray(_getEndTangent, 2),
2351
+ _p = _getEndTangent2[0],
2352
+ _p2 = _getEndTangent2[1];
2353
+ x = _p[0] - _p2[0];
2354
+ y = _p[1] - _p2[1];
2355
+ rad = Math.atan2(y, x);
2356
+ endOffsetX = Math.cos(rad) * (markerEndOffset || 0);
2357
+ endOffsetY = Math.sin(rad) * (markerEndOffset || 0);
2358
+ }
2359
+ for (var i = 0; i < absolutePath.length; i++) {
2360
+ var params = absolutePath[i];
2361
+ var command = params[0];
2362
+ var nextSegment = absolutePath[i + 1];
2363
+ var useStartOffset = i === 0 && (startOffsetX !== 0 || startOffsetY !== 0);
2364
+ var useEndOffset = (i === absolutePath.length - 1 || nextSegment && (nextSegment[0] === 'M' || nextSegment[0] === 'Z')) && endOffsetX !== 0 && endOffsetY !== 0;
2365
+ var _ref = useStartOffset ? [startOffsetX, startOffsetY] : [0, 0],
2366
+ _ref2 = _slicedToArray(_ref, 2),
2367
+ startOffsetXTemp = _ref2[0],
2368
+ startOffsetYTemp = _ref2[1];
2369
+ var _ref3 = useEndOffset ? [endOffsetX, endOffsetY] : [0, 0],
2370
+ _ref4 = _slicedToArray(_ref3, 2),
2371
+ endOffsetXTemp = _ref4[0],
2372
+ endOffsetYTemp = _ref4[1];
2373
+ switch (command) {
2374
+ case 'M':
2375
+ // Use start marker offset
2376
+ context.moveTo(params[1] + startOffsetXTemp, params[2] + startOffsetYTemp);
2377
+ break;
2378
+ case 'L':
2379
+ context.lineTo(params[1] + endOffsetXTemp, params[2] + endOffsetYTemp);
2380
+ break;
2381
+ case 'Q':
2382
+ context.quadraticCurveTo(params[1], params[2], params[3] + endOffsetXTemp, params[4] + endOffsetYTemp);
2383
+ break;
2384
+ case 'C':
2385
+ context.bezierCurveTo(params[1], params[2], params[3], params[4], params[5] + endOffsetXTemp, params[6] + endOffsetYTemp);
2386
+ break;
2387
+ case 'A':
2388
+ {
2389
+ // FIXME startOffset / endOffset
2390
+ var arcParams = segments[i].arcParams;
2391
+ var cx = arcParams.cx,
2392
+ cy = arcParams.cy,
2393
+ rx = arcParams.rx,
2394
+ ry = arcParams.ry,
2395
+ startAngle = arcParams.startAngle,
2396
+ endAngle = arcParams.endAngle,
2397
+ xRotation = arcParams.xRotation,
2398
+ sweepFlag = arcParams.sweepFlag;
2399
+ // @see https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/ellipse
2400
+ if (context.ellipse) {
2401
+ context.ellipse(cx, cy, rx, ry, xRotation, startAngle, endAngle, !!(1 - sweepFlag));
2402
+ } else {
2403
+ // @see https://stackoverflow.com/a/47494351
2404
+ var r = rx > ry ? rx : ry;
2405
+ var scaleX = rx > ry ? 1 : rx / ry;
2406
+ var scaleY = rx > ry ? ry / rx : 1;
2407
+ context.translate(cx, cy);
2408
+ context.rotate(xRotation);
2409
+ context.scale(scaleX, scaleY);
2410
+ context.arc(0, 0, r, startAngle, endAngle, !!(1 - sweepFlag));
2411
+ context.scale(1 / scaleX, 1 / scaleY);
2412
+ context.rotate(-xRotation);
2413
+ context.translate(-cx, -cy);
2414
+ }
2415
+ if (useEndOffset) {
2416
+ context.lineTo(params[6] + endOffsetX, params[7] + endOffsetY);
2417
+ }
2418
+ break;
2419
+ }
2420
+ case 'Z':
2421
+ context.closePath();
2422
+ break;
2423
+ }
2424
+ }
2425
+ }
2426
+
2427
+ function generatePath$2(context, parsedStyle) {
2428
+ var markerStart = parsedStyle.markerStart,
2429
+ markerEnd = parsedStyle.markerEnd,
2430
+ markerStartOffset = parsedStyle.markerStartOffset,
2431
+ markerEndOffset = parsedStyle.markerEndOffset;
2432
+ var points = parsedStyle.points.points;
2433
+ var length = points.length;
2434
+ var x1 = points[0][0];
2435
+ var y1 = points[0][1];
2436
+ var x2 = points[length - 1][0];
2437
+ var y2 = points[length - 1][1];
2438
+ var startOffsetX = 0;
2439
+ var startOffsetY = 0;
2440
+ var endOffsetX = 0;
2441
+ var endOffsetY = 0;
2442
+ var rad = 0;
2443
+ var x;
2444
+ var y;
2445
+ if (markerStart && isDisplayObject(markerStart) && markerStartOffset) {
2446
+ x = points[1][0] - points[0][0];
2447
+ y = points[1][1] - points[0][1];
2448
+ rad = Math.atan2(y, x);
2449
+ startOffsetX = Math.cos(rad) * (markerStartOffset || 0);
2450
+ startOffsetY = Math.sin(rad) * (markerStartOffset || 0);
2451
+ }
2452
+ if (markerEnd && isDisplayObject(markerEnd) && markerEndOffset) {
2453
+ x = points[length - 1][0] - points[0][0];
2454
+ y = points[length - 1][1] - points[0][1];
2455
+ rad = Math.atan2(y, x);
2456
+ endOffsetX = Math.cos(rad) * (markerEndOffset || 0);
2457
+ endOffsetY = Math.sin(rad) * (markerEndOffset || 0);
2458
+ }
2459
+ context.moveTo(x1 + (startOffsetX || endOffsetX), y1 + (startOffsetY || endOffsetY));
2460
+ for (var i = 1; i < length - 1; i++) {
2461
+ var point = points[i];
2462
+ context.lineTo(point[0], point[1]);
2463
+ }
2464
+ context.lineTo(x2, y2);
2465
+ }
2466
+
2467
+ function generatePath$1(context, parsedStyle) {
2468
+ var markerStart = parsedStyle.markerStart,
2469
+ markerEnd = parsedStyle.markerEnd,
2470
+ markerStartOffset = parsedStyle.markerStartOffset,
2471
+ markerEndOffset = parsedStyle.markerEndOffset;
2472
+ var points = parsedStyle.points.points;
2473
+ var length = points.length;
2474
+ var x1 = points[0][0];
2475
+ var y1 = points[0][1];
2476
+ var x2 = points[length - 1][0];
2477
+ var y2 = points[length - 1][1];
2478
+ var startOffsetX = 0;
2479
+ var startOffsetY = 0;
2480
+ var endOffsetX = 0;
2481
+ var endOffsetY = 0;
2482
+ var rad = 0;
2483
+ var x;
2484
+ var y;
2485
+ if (markerStart && isDisplayObject(markerStart) && markerStartOffset) {
2486
+ x = points[1][0] - points[0][0];
2487
+ y = points[1][1] - points[0][1];
2488
+ rad = Math.atan2(y, x);
2489
+ startOffsetX = Math.cos(rad) * (markerStartOffset || 0);
2490
+ startOffsetY = Math.sin(rad) * (markerStartOffset || 0);
2491
+ }
2492
+ if (markerEnd && isDisplayObject(markerEnd) && markerEndOffset) {
2493
+ x = points[length - 2][0] - points[length - 1][0];
2494
+ y = points[length - 2][1] - points[length - 1][1];
2495
+ rad = Math.atan2(y, x);
2496
+ endOffsetX = Math.cos(rad) * (markerEndOffset || 0);
2497
+ endOffsetY = Math.sin(rad) * (markerEndOffset || 0);
2498
+ }
2499
+ context.moveTo(x1 + startOffsetX, y1 + startOffsetY);
2500
+ for (var i = 1; i < length - 1; i++) {
2501
+ var point = points[i];
2502
+ context.lineTo(point[0], point[1]);
2503
+ }
2504
+ context.lineTo(x2 + endOffsetX, y2 + endOffsetY);
2505
+ }
2506
+
2507
+ function generatePath(context, parsedStyle) {
2508
+ var _parsedStyle$x = parsedStyle.x,
2509
+ x = _parsedStyle$x === void 0 ? 0 : _parsedStyle$x,
2510
+ _parsedStyle$y = parsedStyle.y,
2511
+ y = _parsedStyle$y === void 0 ? 0 : _parsedStyle$y,
2512
+ radius = parsedStyle.radius,
2513
+ width = parsedStyle.width,
2514
+ height = parsedStyle.height;
2515
+ var w = width;
2516
+ var h = height;
2517
+ var hasRadius = radius && radius.some(function (r) {
2518
+ return r !== 0;
2519
+ });
2520
+ if (!hasRadius) {
2521
+ // Canvas support negative width/height of rect
2522
+ context.rect(x, y, w, h);
2523
+ } else {
2524
+ var signX = width > 0 ? 1 : -1;
2525
+ var signY = height > 0 ? 1 : -1;
2526
+ var sweepFlag = signX + signY === 0;
2527
+ var _radius$map = radius.map(function (r) {
2528
+ return clamp(r, 0, Math.min(Math.abs(w) / 2, Math.abs(h) / 2));
2529
+ }),
2530
+ _radius$map2 = _slicedToArray(_radius$map, 4),
2531
+ tlr = _radius$map2[0],
2532
+ trr = _radius$map2[1],
2533
+ brr = _radius$map2[2],
2534
+ blr = _radius$map2[3];
2535
+ context.moveTo(signX * tlr + x, y);
2536
+ context.lineTo(w - signX * trr + x, y);
2537
+ if (trr !== 0) {
2538
+ context.arc(w - signX * trr + x, signY * trr + y, trr, -signY * Math.PI / 2, signX > 0 ? 0 : Math.PI, sweepFlag);
2539
+ }
2540
+ context.lineTo(w + x, h - signY * brr + y);
2541
+ if (brr !== 0) {
2542
+ context.arc(w - signX * brr + x, h - signY * brr + y, brr, signX > 0 ? 0 : Math.PI, signY > 0 ? Math.PI / 2 : 1.5 * Math.PI, sweepFlag);
2543
+ }
2544
+ context.lineTo(signX * blr + x, h + y);
2545
+ if (blr !== 0) {
2546
+ context.arc(signX * blr + x, h - signY * blr + y, blr, signY > 0 ? Math.PI / 2 : -Math.PI / 2, signX > 0 ? Math.PI : 0, sweepFlag);
2547
+ }
2548
+ context.lineTo(x, signY * tlr + y);
2549
+ if (tlr !== 0) {
2550
+ context.arc(signX * tlr + x, signY * tlr + y, tlr, signX > 0 ? Math.PI : 0, signY > 0 ? Math.PI * 1.5 : Math.PI / 2, sweepFlag);
2551
+ }
2552
+ }
2553
+ }
2554
+
2555
+ var Plugin = /*#__PURE__*/function (_AbstractRendererPlug) {
2556
+ function Plugin() {
2557
+ var _this;
2558
+ _classCallCheck(this, Plugin);
2559
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
2560
+ args[_key] = arguments[_key];
2561
+ }
2562
+ _this = _callSuper(this, Plugin, [].concat(args));
2563
+ _this.name = 'canvas-path-generator';
2564
+ return _this;
2565
+ }
2566
+ _inherits(Plugin, _AbstractRendererPlug);
2567
+ return _createClass(Plugin, [{
2568
+ key: "init",
2569
+ value: function init() {
2570
+ var _pathGeneratorFactory;
2571
+ var pathGeneratorFactory = (_pathGeneratorFactory = {}, _defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_pathGeneratorFactory, Shape.CIRCLE, generatePath$6), Shape.ELLIPSE, generatePath$5), Shape.RECT, generatePath), Shape.LINE, generatePath$4), Shape.POLYLINE, generatePath$1), Shape.POLYGON, generatePath$2), Shape.PATH, generatePath$3), Shape.TEXT, undefined), Shape.GROUP, undefined), Shape.IMAGE, undefined), _defineProperty(_defineProperty(_defineProperty(_pathGeneratorFactory, Shape.HTML, undefined), Shape.MESH, undefined), Shape.FRAGMENT, undefined));
2572
+
2573
+ // @ts-ignore
2574
+ this.context.pathGeneratorFactory = pathGeneratorFactory;
2575
+ }
2576
+ }, {
2577
+ key: "destroy",
2578
+ value: function destroy() {
2579
+ // @ts-ignore
2580
+ delete this.context.pathGeneratorFactory;
2581
+ }
2582
+ }]);
2583
+ }(AbstractRendererPlugin);
2584
+
2585
+ var index = /*#__PURE__*/Object.freeze({
2586
+ __proto__: null,
2587
+ Plugin: Plugin
2588
+ });
29
2589
 
30
2590
  var Canvas2DContextService = /*#__PURE__*/function () {
31
2591
  function Canvas2DContextService(context) {
@@ -183,12 +2743,12 @@ var Renderer = /*#__PURE__*/function (_AbstractRenderer) {
183
2743
  // register Canvas2DContext
184
2744
  _this.registerPlugin(new ContextRegisterPlugin());
185
2745
  _this.registerPlugin(new ImageLoader.Plugin());
186
- _this.registerPlugin(new CanvasPathGenerator.Plugin());
2746
+ _this.registerPlugin(new Plugin());
187
2747
  // enable rendering with Canvas2D API
188
- _this.registerPlugin(new CanvasRenderer.Plugin());
2748
+ _this.registerPlugin(new Plugin$2());
189
2749
  _this.registerPlugin(new DomInteraction.Plugin());
190
2750
  // enable picking with Canvas2D API
191
- _this.registerPlugin(new CanvasPicker.Plugin());
2751
+ _this.registerPlugin(new Plugin$1());
192
2752
 
193
2753
  // render HTML component
194
2754
  _this.registerPlugin(new HTMLRenderer.Plugin());
@@ -198,5 +2758,5 @@ var Renderer = /*#__PURE__*/function (_AbstractRenderer) {
198
2758
  return _createClass(Renderer);
199
2759
  }(AbstractRenderer);
200
2760
 
201
- export { Renderer };
2761
+ export { index as CanvasPathGenerator, index$1 as CanvasPicker, index$2 as CanvasRenderer, Renderer };
202
2762
  //# sourceMappingURL=index.esm.js.map