-
-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
Pattern.ts
207 lines (185 loc) · 5.64 KB
/
Pattern.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
import { config } from '../config';
import type { Abortable, TCrossOrigin, TMat2D, TSize } from '../typedefs';
import { ifNaN } from '../util/internals';
import { uid } from '../util/internals/uid';
import { loadImage } from '../util/misc/objectEnlive';
import { pick } from '../util/misc/pick';
import { toFixed } from '../util/misc/toFixed';
import { classRegistry } from '../ClassRegistry';
import type {
PatternRepeat,
PatternOptions,
SerializedPatternOptions,
} from './types';
/**
* @see {@link http://fabricjs.com/patterns demo}
* @see {@link http://fabricjs.com/dynamic-patterns demo}
*/
export class Pattern {
static type = 'Pattern';
/**
* Legacy identifier of the class. Prefer using this.constructor.type 'Pattern'
* or utils like isPattern, or instance of to indentify a pattern in your code.
* Will be removed in future versiones
* @TODO add sustainable warning message
* @type string
* @deprecated
*/
get type() {
return 'pattern';
}
set type(value) {
console.warn('Setting type has no effect', value);
}
/**
* @type PatternRepeat
* @defaults
*/
repeat: PatternRepeat = 'repeat';
/**
* Pattern horizontal offset from object's left/top corner
* @type Number
* @default
*/
offsetX = 0;
/**
* Pattern vertical offset from object's left/top corner
* @type Number
* @default
*/
offsetY = 0;
/**
* @type TCrossOrigin
* @default
*/
crossOrigin: TCrossOrigin = '';
/**
* transform matrix to change the pattern, imported from svgs.
* @todo verify if using the identity matrix as default makes the rest of the code more easy
* @type Array
* @default
*/
patternTransform: TMat2D | null = null;
/**
* The actual pixel source of the pattern
*/
declare source: CanvasImageSource;
/**
* If true, this object will not be exported during the serialization of a canvas
* @type boolean
*/
declare excludeFromExport?: boolean;
/**
* ID used for SVG export functionalities
* @type number
*/
declare readonly id: number;
/**
* Constructor
* @param {Object} [options] Options object
* @param {option.source} [source] the pattern source, eventually empty or a drawable
*/
constructor(options: PatternOptions = {}) {
this.id = uid();
Object.assign(this, options);
}
/**
* @returns true if {@link source} is an <img> element
*/
isImageSource(): this is { source: HTMLImageElement } {
return (
!!this.source && typeof (this.source as HTMLImageElement).src === 'string'
);
}
/**
* @returns true if {@link source} is a <canvas> element
*/
isCanvasSource(): this is { source: HTMLCanvasElement } {
return !!this.source && !!(this.source as HTMLCanvasElement).toDataURL;
}
sourceToString(): string {
return this.isImageSource()
? this.source.src
: this.isCanvasSource()
? this.source.toDataURL()
: '';
}
/**
* Returns an instance of CanvasPattern
* @param {CanvasRenderingContext2D} ctx Context to create pattern
* @return {CanvasPattern}
*/
toLive(ctx: CanvasRenderingContext2D): CanvasPattern | null {
if (
// if the image failed to load, return, and allow rest to continue loading
!this.source ||
// if an image
(this.isImageSource() &&
(!this.source.complete ||
this.source.naturalWidth === 0 ||
this.source.naturalHeight === 0))
) {
return null;
}
return ctx.createPattern(this.source, this.repeat)!;
}
/**
* Returns object representation of a pattern
* @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
* @return {object} Object representation of a pattern instance
*/
toObject(propertiesToInclude: string[] = []): Record<string, any> {
const { repeat, crossOrigin } = this;
return {
...pick(this, propertiesToInclude as (keyof this)[]),
type: 'pattern',
source: this.sourceToString(),
repeat,
crossOrigin,
offsetX: toFixed(this.offsetX, config.NUM_FRACTION_DIGITS),
offsetY: toFixed(this.offsetY, config.NUM_FRACTION_DIGITS),
patternTransform: this.patternTransform
? [...this.patternTransform]
: null,
};
}
/* _TO_SVG_START_ */
/**
* Returns SVG representation of a pattern
*/
toSVG({ width, height }: TSize): string {
const { source: patternSource, repeat, id } = this,
patternOffsetX = ifNaN(this.offsetX / width, 0),
patternOffsetY = ifNaN(this.offsetY / height, 0),
patternWidth =
repeat === 'repeat-y' || repeat === 'no-repeat'
? 1 + Math.abs(patternOffsetX || 0)
: ifNaN((patternSource.width as number) / width, 0),
patternHeight =
repeat === 'repeat-x' || repeat === 'no-repeat'
? 1 + Math.abs(patternOffsetY || 0)
: ifNaN((patternSource.height as number) / height, 0);
return [
`<pattern id="SVGID_${id}" x="${patternOffsetX}" y="${patternOffsetY}" width="${patternWidth}" height="${patternHeight}">`,
`<image x="0" y="0" width="${patternSource.width}" height="${
patternSource.height
}" xlink:href="${this.sourceToString()}"></image>`,
`</pattern>`,
'',
].join('\n');
}
/* _TO_SVG_END_ */
static async fromObject(
{ source, ...serialized }: SerializedPatternOptions,
options: Abortable
): Promise<Pattern> {
const img = await loadImage(source, {
...options,
crossOrigin: serialized.crossOrigin,
});
return new this({ ...serialized, source: img });
}
}
classRegistry.setClass(Pattern);
// kept for compatibility reason
classRegistry.setClass(Pattern, 'pattern');