-
-
Notifications
You must be signed in to change notification settings - Fork 114
/
atrament.js
executable file
·407 lines (343 loc) · 11.9 KB
/
atrament.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
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
const { Mouse, Point } = require('./mouse.js');
const Constants = require('./constants.js');
const { AtramentEventTarget } = require('./events.js');
const Pixels = require('./pixels.js');
module.exports = class Atrament extends AtramentEventTarget {
constructor(selector, config = {}) {
if (typeof window === 'undefined') {
throw new Error('Looks like we\'re not running in a browser');
}
super();
// get canvas element
if (selector instanceof window.Node && selector.tagName === 'CANVAS') this.canvas = selector;
else if (typeof selector === 'string') this.canvas = document.querySelector(selector);
else throw new Error(`can't look for canvas based on '${selector}'`);
if (!this.canvas) throw new Error('canvas not found');
// set external canvas params
this.canvas.width = config.width || this.canvas.width;
this.canvas.height = config.height || this.canvas.height;
// create a mouse object
this.mouse = new Mouse();
// mousemove handler
const mouseMove = (e) => {
if (e.cancelable) {
e.preventDefault();
}
const rect = this.canvas.getBoundingClientRect();
const position = e.changedTouches && e.changedTouches[0] || e;
let x = position.offsetX;
let y = position.offsetY;
if (typeof x === 'undefined') {
x = position.clientX - rect.left;
}
if (typeof y === 'undefined') {
y = position.clientY - rect.top;
}
// draw if we should draw
if (this.mouse.down && this._mode === 'draw') {
this.draw(x, y);
if (this.recordStrokes) {
this.strokeMemory.push(new Point(x, y));
}
if (!this._dirty && (x !== this.mouse.x || y !== this.mouse.y)) {
this._dirty = true;
this.fireDirty();
}
}
else {
this.mouse.set(x, y);
}
};
// mousedown handler
const mouseDown = (mouse) => {
if (mouse.cancelable) {
mouse.preventDefault();
}
// update position just in case
mouseMove(mouse);
// if we are filling - fill and return
if (this._mode === 'fill') {
this.fill();
return;
}
// remember it
this.mouse.px = this.mouse.x;
this.mouse.py = this.mouse.y;
this.mouse.down = true;
this.beginDrawing();
};
const mouseUp = (e) => {
if (this.mode === 'fill') {
return;
}
const position = e.changedTouches && e.changedTouches[0] || e;
const x = position.offsetX;
const y = position.offsetY;
this.mouse.down = false;
if (this.mouse.x === x && this.mouse.y === y && this.mode === 'draw') {
this.draw(this.mouse.x, this.mouse.y);
}
this.stopDrawing();
};
// attach listeners
this.canvas.addEventListener('mousemove', mouseMove);
this.canvas.addEventListener('mousedown', mouseDown);
document.addEventListener('mouseup', mouseUp);
this.canvas.addEventListener('touchstart', mouseDown);
this.canvas.addEventListener('touchend', mouseUp);
this.canvas.addEventListener('touchmove', mouseMove);
// helper for destroying Atrament (removing event listeners)
this.destroy = () => {
this.clear();
this.canvas.removeEventListener('mousemove', mouseMove);
this.canvas.removeEventListener('mousedown', mouseDown);
document.removeEventListener('mouseup', mouseUp);
this.canvas.removeEventListener('touchstart', mouseDown);
this.canvas.removeEventListener('touchend', mouseUp);
this.canvas.removeEventListener('touchmove', mouseMove);
};
// set internal canvas params
this.context = this.canvas.getContext('2d');
this.context.globalCompositeOperation = 'source-over';
this.context.globalAlpha = 1;
this.context.strokeStyle = config.color || 'rgba(0,0,0,1)';
this.context.lineCap = 'round';
this.context.lineJoin = 'round';
this.context.translate(0.5, 0.5);
this._filling = false;
this._fillStack = [];
// set drawing params
this.recordStrokes = false;
this.strokeMemory = [];
this.smoothing = Constants.initialSmoothingFactor;
this._thickness = Constants.initialThickness;
this._targetThickness = this._thickness;
this._weight = this._thickness;
this._maxWeight = this._thickness + Constants.weightSpread;
this._mode = 'draw';
this.adaptiveStroke = true;
// update from config object
['weight', 'smoothing', 'adaptiveStroke', 'mode', 'opacity']
.forEach(key => config[key] === undefined ? 0 : this[key] = config[key]);
}
beginDrawing() {
this.context.beginPath();
this.context.moveTo(this.mouse.px, this.mouse.py);
this.dispatchEvent('strokestart', {});
}
stopDrawing() {
this.context.closePath();
this.dispatchEvent('strokeend', {});
if (this.recordStrokes) {
const stroke = {
points: this.strokeMemory.slice(),
weight: this.weight,
opacity: this.opacity,
smoothing: this.smoothing,
color: this.color,
adaptiveStroke: this.adaptiveStroke
};
this.dispatchEvent('strokerecorded', { stroke });
}
this.strokeMemory = [];
}
draw(mX, mY) {
const { mouse } = this;
const { context } = this;
// calculate distance from previous point
const rawDist = Pixels.lineDistance(mX, mY, mouse.px, mouse.py);
// now, here we scale the initial smoothing factor by the raw distance
// this means that when the mouse moves fast, there is more smoothing
// and when we're drawing small detailed stuff, we have more control
// also we hard clip at 1
const smoothingFactor = Math.min(Constants.minSmoothingFactor, this.smoothing + (rawDist - 60) / 3000);
// calculate smoothed coordinates
mouse.x = mX - (mX - mouse.px) * smoothingFactor;
mouse.y = mY - (mY - mouse.py) * smoothingFactor;
// recalculate distance from previous point, this time relative to the smoothed coords
const dist = Pixels.lineDistance(mouse.x, mouse.y, mouse.px, mouse.py);
if (this.adaptiveStroke) {
// calculate target thickness based on the new distance
this._targetThickness = (dist - Constants.minLineThickness)
/ Constants.lineThicknessRange * (this._maxWeight - this._weight) + this._weight;
// approach the target gradually
if (this._thickness > this._targetThickness) {
this._thickness -= Constants.thicknessIncrement;
}
else if (this._thickness < this._targetThickness) {
this._thickness += Constants.thicknessIncrement;
}
// set line width
context.lineWidth = this._thickness;
}
else {
// line width is equal to default weight
context.lineWidth = this._weight;
}
// draw using quad interpolation
context.quadraticCurveTo(mouse.px, mouse.py, mouse.x, mouse.y);
context.stroke();
// remember
mouse.px = mouse.x;
mouse.py = mouse.y;
}
get color() {
return this.context.strokeStyle;
}
set color(c) {
if (typeof c !== 'string') throw new Error('wrong argument type');
this.context.strokeStyle = c;
}
get weight() {
return this._weight;
}
set weight(w) {
if (typeof w !== 'number') throw new Error('wrong argument type');
this._weight = w;
this._thickness = w;
this._targetThickness = w;
this._maxWeight = w + Constants.weightSpread;
}
get mode() {
return this._mode;
}
set mode(m) {
if (typeof m !== 'string') throw new Error('wrong argument type');
switch (m) {
case 'erase':
this._mode = 'erase';
this.context.globalCompositeOperation = 'destination-out';
break;
case 'fill':
this._mode = 'fill';
this.context.globalCompositeOperation = 'source-over';
break;
default:
this._mode = 'draw';
this.context.globalCompositeOperation = 'source-over';
break;
}
}
set opacity(o) {
if (typeof o !== 'number') throw new Error('wrong argument type');
// now, we need to scale this, because our drawing method means we don't just get uniform transparency all over the drawn line.
// so we scale it down a lot, meaning that it'll look nicely semi-transparent
// unless opacity is 1, then we should go full on to 1
if (o >= 1) this.context.globalAlpha = 1;
else this.context.globalAlpha = o / 10;
}
isDirty() {
return !!this._dirty;
}
fireDirty() {
this.dispatchEvent('dirty');
}
clear() {
if (!this.isDirty) {
return;
}
this._dirty = false;
this.dispatchEvent('clean');
// make sure we're in the right compositing mode, and erase everything
if (this.mode === 'erase') {
this.mode = 'draw';
this.context.clearRect(-10, -10, this.canvas.width + 20, this.canvas.height + 20);
this.mode = 'erase';
}
else {
this.context.clearRect(-10, -10, this.canvas.width + 20, this.canvas.height + 20);
}
}
toImage() {
return this.canvas.toDataURL();
}
fill() {
const { mouse } = this;
const { context } = this;
// converting to Array because Safari 9
const startColor = Array.from(context.getImageData(mouse.x, mouse.y, 1, 1).data);
if (!this._filling) {
const { x, y } = mouse;
this.dispatchEvent('fillstart', { x, y });
this._filling = true;
setTimeout(() => { this._floodFill(mouse.x, mouse.y, startColor); }, Constants.floodFillInterval);
}
else {
this._fillStack.push([
mouse.x,
mouse.y,
startColor
]);
}
}
_floodFill(_startX, _startY, startColor) {
const { context } = this;
const startX = Math.floor(_startX);
const startY = Math.floor(_startY);
const canvasWidth = context.canvas.width;
const canvasHeight = context.canvas.height;
const pixelStack = [[startX, startY]];
// hex needs to be trasformed to rgb since colorLayer accepts RGB
const fillColor = Pixels.hexToRgb(this.color);
// Need to save current context with colors, we will update it
const colorLayer = context.getImageData(0, 0, context.canvas.width, context.canvas.height);
const alpha = Math.min(context.globalAlpha * 10 * 255, 255);
const colorPixel = Pixels.colorPixel(colorLayer.data, ...fillColor, startColor, alpha);
const matchColor = Pixels.matchColor(colorLayer.data, ...startColor);
const matchFillColor = Pixels.matchColor(colorLayer.data, ...[...fillColor, 255]);
// check if we're trying to fill with the same colour, if so, stop
if (matchFillColor((startY * context.canvas.width + startX) * 4)) {
this._filling = false;
this.dispatchEvent('fillend', {});
return;
}
while (pixelStack.length) {
const newPos = pixelStack.pop();
const x = newPos[0];
let y = newPos[1];
let pixelPos = (y * canvasWidth + x) * 4;
while (y-- >= 0 && matchColor(pixelPos)) {
pixelPos -= canvasWidth * 4;
}
pixelPos += canvasWidth * 4;
++y;
let reachLeft = false;
let reachRight = false;
while (y++ < canvasHeight - 1 && matchColor(pixelPos)) {
colorPixel(pixelPos);
if (x > 0) {
if (matchColor(pixelPos - 4)) {
if (!reachLeft) {
pixelStack.push([x - 1, y]);
reachLeft = true;
}
}
else if (reachLeft) {
reachLeft = false;
}
}
if (x < canvasWidth - 1) {
if (matchColor(pixelPos + 4)) {
if (!reachRight) {
pixelStack.push([x + 1, y]);
reachRight = true;
}
}
else if (reachRight) {
reachRight = false;
}
}
pixelPos += canvasWidth * 4;
}
}
// Update context with filled bucket!
context.putImageData(colorLayer, 0, 0);
if (this._fillStack.length) {
this._floodFill(...this._fillStack.shift());
}
else {
this._filling = false;
this.dispatchEvent('fillend', {});
}
}
};