-
-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
Copy pathPath.ts
421 lines (377 loc) · 11.2 KB
/
Path.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
import { config } from '../config';
import { SHARED_ATTRIBUTES } from '../parser/attributes';
import { parseAttributes } from '../parser/parseAttributes';
import type { XY } from '../Point';
import { Point } from '../Point';
import { makeBoundingBoxFromPoints } from '../util/misc/boundingBoxFromPoints';
import { toFixed } from '../util/misc/toFixed';
import {
getBoundsOfCurve,
joinPath,
makePathSimpler,
parsePath,
} from '../util/path';
import { classRegistry } from '../ClassRegistry';
import { FabricObject, cacheProperties } from './Object/FabricObject';
import type {
TComplexPathData,
TPathSegmentInfo,
TSimplePathData,
} from '../util/path/typedefs';
import type { FabricObjectProps, SerializedObjectProps } from './Object/types';
import type { ObjectEvents } from '../EventTypeDefs';
import type {
TBBox,
TClassProperties,
TSVGReviver,
TOptions,
} from '../typedefs';
import { CENTER, LEFT, TOP } from '../constants';
import type { CSSRules } from '../parser/typedefs';
interface UniquePathProps {
sourcePath?: string;
path?: TSimplePathData;
}
export interface SerializedPathProps
extends SerializedObjectProps,
UniquePathProps {}
export interface PathProps extends FabricObjectProps, UniquePathProps {}
export interface IPathBBox extends TBBox {
left: number;
top: number;
pathOffset: Point;
}
export class Path<
Props extends TOptions<PathProps> = Partial<PathProps>,
SProps extends SerializedPathProps = SerializedPathProps,
EventSpec extends ObjectEvents = ObjectEvents,
> extends FabricObject<Props, SProps, EventSpec> {
/**
* Array of path points
* @type Array
* @default
*/
declare path: TSimplePathData;
declare pathOffset: Point;
declare sourcePath?: string;
declare segmentsInfo?: TPathSegmentInfo[];
static type = 'Path';
static cacheProperties = [...cacheProperties, 'path', 'fillRule'];
/**
* Constructor
* @param {TComplexPathData} path Path data (sequence of coordinates and corresponding "command" tokens)
* @param {Partial<PathProps>} [options] Options object
* @return {Path} thisArg
*/
constructor(
path: TComplexPathData | string,
// todo: evaluate this spread here
{ path: _, left, top, ...options }: Partial<Props> = {},
) {
super();
Object.assign(this, Path.ownDefaults);
this.setOptions(options);
this._setPath(path || [], true);
typeof left === 'number' && this.set(LEFT, left);
typeof top === 'number' && this.set(TOP, top);
}
/**
* @private
* @param {TComplexPathData | string} path Path data (sequence of coordinates and corresponding "command" tokens)
* @param {boolean} [adjustPosition] pass true to reposition the object according to the bounding box
* @returns {Point} top left position of the bounding box, useful for complementary positioning
*/
_setPath(path: TComplexPathData | string, adjustPosition?: boolean) {
this.path = makePathSimpler(Array.isArray(path) ? path : parsePath(path));
this.setBoundingBox(adjustPosition);
}
/**
* This function is an helper for svg import. it returns the center of the object in the svg
* untransformed coordinates, by look at the polyline/polygon points.
* @private
* @return {Point} center point from element coordinates
*/
_findCenterFromElement(): Point {
const bbox = this._calcBoundsFromPath();
return new Point(bbox.left + bbox.width / 2, bbox.top + bbox.height / 2);
}
/**
* @private
* @param {CanvasRenderingContext2D} ctx context to render path on
*/
_renderPathCommands(ctx: CanvasRenderingContext2D) {
const l = -this.pathOffset.x,
t = -this.pathOffset.y;
ctx.beginPath();
for (const command of this.path) {
switch (
command[0] // first letter
) {
case 'L': // lineto, absolute
ctx.lineTo(command[1] + l, command[2] + t);
break;
case 'M': // moveTo, absolute
ctx.moveTo(command[1] + l, command[2] + t);
break;
case 'C': // bezierCurveTo, absolute
ctx.bezierCurveTo(
command[1] + l,
command[2] + t,
command[3] + l,
command[4] + t,
command[5] + l,
command[6] + t,
);
break;
case 'Q': // quadraticCurveTo, absolute
ctx.quadraticCurveTo(
command[1] + l,
command[2] + t,
command[3] + l,
command[4] + t,
);
break;
case 'Z':
ctx.closePath();
break;
}
}
}
/**
* @private
* @param {CanvasRenderingContext2D} ctx context to render path on
*/
_render(ctx: CanvasRenderingContext2D) {
this._renderPathCommands(ctx);
this._renderPaintInOrder(ctx);
}
/**
* Returns string representation of an instance
* @return {string} string representation of an instance
*/
toString() {
return `#<Path (${this.complexity()}): { "top": ${this.top}, "left": ${
this.left
} }>`;
}
/**
* Returns object representation of an instance
* @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
* @return {Object} object representation of an instance
*/
toObject<
T extends Omit<Props & TClassProperties<this>, keyof SProps>,
K extends keyof T = never,
>(propertiesToInclude: K[] = []): Pick<T, K> & SProps {
return {
...super.toObject(propertiesToInclude),
path: this.path.map((pathCmd) => pathCmd.slice()),
};
}
/**
* Returns dataless object representation of an instance
* @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
* @return {Object} object representation of an instance
*/
toDatalessObject<
T extends Omit<Props & TClassProperties<this>, keyof SProps>,
K extends keyof T = never,
>(propertiesToInclude: K[] = []): Pick<T, K> & SProps {
const o = this.toObject<T, K>(propertiesToInclude);
if (this.sourcePath) {
delete o.path;
o.sourcePath = this.sourcePath;
}
return o;
}
/**
* Returns svg representation of an instance
* @return {Array} an array of strings with the specific svg representation
* of the instance
*/
_toSVG() {
const path = joinPath(this.path, config.NUM_FRACTION_DIGITS);
return [
'<path ',
'COMMON_PARTS',
`d="${path}" stroke-linecap="round" />\n`,
];
}
/**
* @private
* @return the path command's translate transform attribute
*/
_getOffsetTransform() {
const digits = config.NUM_FRACTION_DIGITS;
return ` translate(${toFixed(-this.pathOffset.x, digits)}, ${toFixed(
-this.pathOffset.y,
digits,
)})`;
}
/**
* Returns svg clipPath representation of an instance
* @param {Function} [reviver] Method for further parsing of svg representation.
* @return {string} svg representation of an instance
*/
toClipPathSVG(reviver?: TSVGReviver): string {
const additionalTransform = this._getOffsetTransform();
return (
'\t' +
this._createBaseClipPathSVGMarkup(this._toSVG(), {
reviver,
additionalTransform: additionalTransform,
})
);
}
/**
* Returns svg representation of an instance
* @param {Function} [reviver] Method for further parsing of svg representation.
* @return {string} svg representation of an instance
*/
toSVG(reviver?: TSVGReviver): string {
const additionalTransform = this._getOffsetTransform();
return this._createBaseSVGMarkup(this._toSVG(), {
reviver,
additionalTransform: additionalTransform,
});
}
/**
* Returns number representation of an instance complexity
* @return {number} complexity of this instance
*/
complexity() {
return this.path.length;
}
setDimensions() {
this.setBoundingBox();
}
setBoundingBox(adjustPosition?: boolean) {
const { width, height, pathOffset } = this._calcDimensions();
this.set({ width, height, pathOffset });
// using pathOffset because it match the use case.
// if pathOffset change here we need to use left + width/2 , top + height/2
adjustPosition && this.setPositionByOrigin(pathOffset, CENTER, CENTER);
}
_calcBoundsFromPath(): TBBox {
const bounds: XY[] = [];
let subpathStartX = 0,
subpathStartY = 0,
x = 0, // current x
y = 0; // current y
for (const command of this.path) {
// current instruction
switch (
command[0] // first letter
) {
case 'L': // lineto, absolute
x = command[1];
y = command[2];
bounds.push({ x: subpathStartX, y: subpathStartY }, { x, y });
break;
case 'M': // moveTo, absolute
x = command[1];
y = command[2];
subpathStartX = x;
subpathStartY = y;
break;
case 'C': // bezierCurveTo, absolute
bounds.push(
...getBoundsOfCurve(
x,
y,
command[1],
command[2],
command[3],
command[4],
command[5],
command[6],
),
);
x = command[5];
y = command[6];
break;
case 'Q': // quadraticCurveTo, absolute
bounds.push(
...getBoundsOfCurve(
x,
y,
command[1],
command[2],
command[1],
command[2],
command[3],
command[4],
),
);
x = command[3];
y = command[4];
break;
case 'Z':
x = subpathStartX;
y = subpathStartY;
break;
}
}
return makeBoundingBoxFromPoints(bounds);
}
/**
* @private
*/
_calcDimensions(): IPathBBox {
const bbox = this._calcBoundsFromPath();
return {
...bbox,
pathOffset: new Point(
bbox.left + bbox.width / 2,
bbox.top + bbox.height / 2,
),
};
}
/**
* List of attribute names to account for when parsing SVG element (used by `Path.fromElement`)
* @static
* @memberOf Path
* @see http://www.w3.org/TR/SVG/paths.html#PathElement
*/
static ATTRIBUTE_NAMES = [...SHARED_ATTRIBUTES, 'd'];
/**
* Creates an instance of Path from an object
* @static
* @memberOf Path
* @param {Object} object
* @returns {Promise<Path>}
*/
static fromObject<T extends TOptions<SerializedPathProps>>(object: T) {
return this._fromObject<Path>(object, {
extraParam: 'path',
});
}
/**
* Creates an instance of Path from an SVG <path> element
* @static
* @memberOf Path
* @param {HTMLElement} element to parse
* @param {Partial<PathProps>} [options] Options object
*/
static async fromElement(
element: HTMLElement,
options: Partial<PathProps>,
cssRules?: CSSRules,
) {
const { d, ...parsedAttributes } = parseAttributes(
element,
this.ATTRIBUTE_NAMES,
cssRules,
);
return new this(d, {
...parsedAttributes,
...options,
// we pass undefined to instruct the constructor to position the object using the bbox
left: undefined,
top: undefined,
});
}
}
classRegistry.setClass(Path);
classRegistry.setSVGClass(Path);
/* _FROM_SVG_START_ */