forked from mezzoblue/PaintbrushJS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpaintbrush.js
540 lines (441 loc) · 16.1 KB
/
paintbrush.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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
var Canvas = require('canvas')
/*
// function to process all filters
// (exists outside of loader to enable standalone use)
function processFilters() {
// create working buffer outside the main loop so it's only done once
var buffer = document.createElement("canvas");
// get the canvas context
var c = buffer.getContext('2d');
// only run if this browser supports canvas, obviously
if (supports_canvas()) {
// you can add or remove lines here, depending on which filters you're using.
addFilter("filter-blur", buffer, c);
addFilter("filter-edges", buffer, c);
addFilter("filter-emboss", buffer, c);
addFilter("filter-greyscale", buffer, c);
addFilter("filter-matrix", buffer, c);
addFilter("filter-mosaic", buffer, c);
addFilter("filter-noise", buffer, c);
addFilter("filter-posterize", buffer, c);
addFilter("filter-sepia", buffer, c);
addFilter("filter-sharpen", buffer, c);
addFilter("filter-tint", buffer, c);
}
}
*/
// the main workhorse function
//function addFilter(filterType, buffer, c) {
exports.process = function(img, filterType, buffer, c) {
/*
// get every element with the specified filter class
var toFilter = getElementsByClassName(filterType.toLowerCase());
// now let's loop through those elements
for(var current in toFilter) {
// load all specified parameters for this filter
var params = getFilterParameters(toFilter[current]);
// get the image we're going to work with
var img = getReferenceImage(toFilter[current]);
// make sure we've actually got something to work with
img.onLoad = processFilters(filterType, img, params, toFilter, current, buffer, c);
}
*/
var params = {
"blurAmount" : 1, // 0 and higher
"edgesAmount" : 1, // between 0 and 1
"embossAmount" : 0.25, // between 0 and 1
"greyscaleOpacity" : 1, // between 0 and 1
"matrixAmount" : 1, // between 0 and 1
"mosaicOpacity" : 1, // between 0 and 1
"mosaicSize" : 5, // 1 and higher
"noiseAmount" : 30, // 0 and higher
"noiseType" : "mono", // mono or color
"posterizeAmount" : 5, // 0 - 255, though 0 and 1 are relatively useless
"posterizeOpacity" : 1, // between 0 and 1
"sepiaOpacity" : 1, // between 0 and 1
"sharpenAmount" : 0.25, // between 0 and 1
"tintColor" : "#FFF", // any hex color
"tintOpacity" : 0.3 // between 0 and 1
}
//img = 'foo'; // TODO: need img reference
if(img){
processFilters(filterType, img, params, buffer, c);
}
function processFilters(filterType, img, params, buffer, c) {
// quick access to original element
//var ref = toFilter[current];
// original image copy naming convention
//var originalSuffix = filterType + "-" + current;
// set buffer dimensions to image dimensions
c.width = buffer.width = img.width;
c.height = buffer.height = img.height;
if (img && c) {
// create the temporary pixel array we'll be manipulating
var pixels = initializeBuffer(c, img);
if (pixels) {
//
// pre-processing for various filters
//
// blur and all matrix filters have to exist outside the main loop
if (filterType == "filter-blur") {
pixels = gaussianBlur(img, pixels, params.blurAmount);
}
if (filterType == "filter-edges") {
var matrix = [
0, 1, 0,
1, -4, 1,
0, 1, 0
];
pixels = applyMatrix(img, pixels, matrix, params.edgesAmount);
}
if (filterType == "filter-emboss") {
var matrix = [
-2, -1, 0,
-1, 1, 1,
0, 1, 2
];
pixels = applyMatrix(img, pixels, matrix, params.embossAmount);
}
if (filterType == "filter-matrix") {
// 3x3 matrix can be any combination of digits, though to maintain brightness they should add up to 1
// (-1 x 8 + 9 = 1)
var matrix = [
// box blur default
0.111, 0.111, 0.111,
0.111, 0.111, 0.111,
0.111, 0.111, 0.111
];
pixels = applyMatrix(img, pixels, matrix, params.matrixAmount);
}
if (filterType == "filter-sharpen") {
var matrix = [
-1, -1, -1,
-1, 9, -1,
-1, -1, -1
];
pixels = applyMatrix(img, pixels, matrix, params.sharpenAmount);
}
// we need to figure out RGB values for tint, let's do that ahead and not waste time in the loop
if (filterType == "filter-tint") {
var src = parseInt(createColor(params.tintColor), 16),
dest = {r: ((src & 0xFF0000) >> 16), g: ((src & 0x00FF00) >> 8), b: (src & 0x0000FF)};
}
if ((filterType != "filter-blur")
&& (filterType != "filter-emboss")
&& (filterType != "filter-matrix")
&& (filterType != "filter-sharpen")
) {
// the main loop through every pixel to apply the simpler effects
// (data is per-byte, and there are 4 bytes per pixel, so lets only loop through each pixel and save a few cycles)
for (var i = 0, data = pixels.data, length = data.length; i < length >> 2; i++) {
var index = i << 2;
// get each colour value of current pixel
var thisPixel = {r: data[index], g: data[index + 1], b: data[index + 2]};
// the biggie: if we're here, let's get some filter action happening
pixels = applyFilters(filterType, params, img, pixels, index, thisPixel, dest);
}
}
// redraw the pixel data back to the working buffer
c.putImageData(pixels, 0, 0);
// stash a copy and let the original know how to reference it
//stashOriginal(img, originalSuffix, ref, buffer);
}
}
}
// the function that actually manipulates the pixels
function applyFilters(filterType, params, img, pixels, index, thisPixel, dest) {
// speed up access
var data = pixels.data, val;
var imgWidth = img.width;
// figure out which filter to apply, and do it
switch(filterType) {
case "filter-greyscale":
val = (thisPixel.r * 0.21) + (thisPixel.g * 0.71) + (thisPixel.b * 0.07);
data = setRGB(data, index,
findColorDifference(params.greyscaleOpacity, val, thisPixel.r),
findColorDifference(params.greyscaleOpacity, val, thisPixel.g),
findColorDifference(params.greyscaleOpacity, val, thisPixel.b));
break;
case "filter-mosaic":
// a bit more verbose to reduce amount of math necessary
var pos = index >> 2;
var stepY = Math.floor(pos / imgWidth);
var stepY1 = stepY % params.mosaicSize;
var stepX = pos - (stepY * imgWidth);
var stepX1 = stepX % params.mosaicSize;
if (stepY1) pos -= stepY1 * imgWidth;
if (stepX1) pos -= stepX1;
pos = pos << 2;
data = setRGB(data, index,
findColorDifference(params.mosaicOpacity, data[pos], thisPixel.r),
findColorDifference(params.mosaicOpacity, data[pos + 1], thisPixel.g),
findColorDifference(params.mosaicOpacity, data[pos + 2], thisPixel.b));
break;
case "filter-noise":
val = noise(params.noiseAmount);
if ((params.noiseType == "mono") || (params.noiseType == "monochrome")) {
data = setRGB(data, index,
checkRGBBoundary(thisPixel.r + val),
checkRGBBoundary(thisPixel.g + val),
checkRGBBoundary(thisPixel.b + val));
} else {
data = setRGB(data, index,
checkRGBBoundary(thisPixel.r + noise(params.noiseAmount)),
checkRGBBoundary(thisPixel.g + noise(params.noiseAmount)),
checkRGBBoundary(thisPixel.b + noise(params.noiseAmount)));
}
break;
case "filter-posterize":
data = setRGB(data, index,
findColorDifference(params.posterizeOpacity, parseInt(params.posterizeValues * parseInt(thisPixel.r / params.posterizeAreas)), thisPixel.r),
findColorDifference(params.posterizeOpacity, parseInt(params.posterizeValues * parseInt(thisPixel.g / params.posterizeAreas)), thisPixel.g),
findColorDifference(params.posterizeOpacity, parseInt(params.posterizeValues * parseInt(thisPixel.b / params.posterizeAreas)), thisPixel.b));
break;
case "filter-sepia":
data = setRGB(data, index,
findColorDifference(params.sepiaOpacity, (thisPixel.r * 0.393) + (thisPixel.g * 0.769) + (thisPixel.b * 0.189), thisPixel.r),
findColorDifference(params.sepiaOpacity, (thisPixel.r * 0.349) + (thisPixel.g * 0.686) + (thisPixel.b * 0.168), thisPixel.g),
findColorDifference(params.sepiaOpacity, (thisPixel.r * 0.272) + (thisPixel.g * 0.534) + (thisPixel.b * 0.131), thisPixel.b));
break;
case "filter-tint":
data = setRGB(data, index,
findColorDifference(params.tintOpacity, dest.r, thisPixel.r),
findColorDifference(params.tintOpacity, dest.g, thisPixel.g),
findColorDifference(params.tintOpacity, dest.b, thisPixel.b));
break;
}
return(pixels);
}
// apply a convolution matrix
function applyMatrix(img, pixels, matrix, amount) {
console.log('here')
var buffer2 = new Canvas(1,1);
var c2 = buffer2.getContext('2d');
console.log('here')
// create a second buffer to hold matrix results
//var buffer2 = document.createElement("canvas");
// get the canvas context
//var c2 = buffer2.getContext('2d');
// set the dimensions
c2.width = buffer2.width = img.width;
c2.height = buffer2.height = img.height;
// draw the image to the new buffer
c2.drawImage(img, 0, 0, img.width , img.height);
var bufferedPixels = c2.getImageData(0, 0, c.width, c.height)
// speed up access
var data = pixels.data, bufferedData = bufferedPixels.data, imgWidth = img.width;
// make sure the matrix adds up to 1
/* matrix = normalizeMatrix(matrix); */
// calculate the dimensions, just in case this ever expands to 5 and beyond
var matrixSize = Math.sqrt(matrix.length);
// loop through every pixel
for (var i = 1; i < imgWidth - 1; i++) {
for (var j = 1; j < img.height - 1; j++) {
// temporary holders for matrix results
var sumR = sumG = sumB = 0;
// loop through the matrix itself
for (var h = 0; h < matrixSize; h++) {
for (var w = 0; w < matrixSize; w++) {
// get a refence to a pixel position in the matrix
var r = convertCoordinates(i + h - 1, j + w - 1, imgWidth) << 2;
// find RGB values for that pixel
var currentPixel = {
r: bufferedData[r],
g: bufferedData[r + 1],
b: bufferedData[r + 2]
};
// apply the value from the current matrix position
sumR += currentPixel.r * matrix[w + h * matrixSize];
sumG += currentPixel.g * matrix[w + h * matrixSize];
sumB += currentPixel.b * matrix[w + h * matrixSize];
}
}
// get a reference for the final pixel
var ref = convertCoordinates(i, j, imgWidth) << 2;
var thisPixel = {
r: data[ref],
g: data[ref + 1],
b: data[ref + 2]
};
// finally, apply the adjusted values
data = setRGB(data, ref,
findColorDifference(amount, sumR, thisPixel.r),
findColorDifference(amount, sumG, thisPixel.g),
findColorDifference(amount, sumB, thisPixel.b));
}
}
// code to clean the secondary buffer out of the DOM would be good here
return(pixels);
}
// ensure that values in a matrix add up to 1
function normalizeMatrix(matrix) {
var j = 0;
for (var i = 0; i < matrix.length; i++) {
j += matrix[i];
}
for (var i = 0; i < matrix.length; i++) {
matrix[i] /= j;
}
return matrix;
}
// convert x/y coordinates to pixel index reference
function convertCoordinates(x, y, w) {
return x + (y * w);
}
// calculate random noise. different every time!
function noise(noiseValue) {
return Math.floor((noiseValue >> 1) - (Math.random() * noiseValue));
}
// ensure an RGB value isn't negative / over 255
function checkRGBBoundary(val) {
if (val < 0) {
return 0;
} else if (val > 255) {
return 255;
} else {
return val;
}
}
}
// calculate gaussian blur
// adapted from http://pvnick.blogspot.com/2010/01/im-currently-porting-image-segmentation.html
function gaussianBlur(img, pixels, amount) {
var width = img.width;
var width4 = width << 2;
var height = img.height;
if (pixels) {
var data = pixels.data;
// compute coefficients as a function of amount
var q;
if (amount < 0.0) {
amount = 0.0;
}
if (amount >= 2.5) {
q = 0.98711 * amount - 0.96330;
} else if (amount >= 0.5) {
q = 3.97156 - 4.14554 * Math.sqrt(1.0 - 0.26891 * amount);
} else {
q = 2 * amount * (3.97156 - 4.14554 * Math.sqrt(1.0 - 0.26891 * 0.5));
}
//compute b0, b1, b2, and b3
var qq = q * q;
var qqq = qq * q;
var b0 = 1.57825 + (2.44413 * q) + (1.4281 * qq ) + (0.422205 * qqq);
var b1 = ((2.44413 * q) + (2.85619 * qq) + (1.26661 * qqq)) / b0;
var b2 = (-((1.4281 * qq) + (1.26661 * qqq))) / b0;
var b3 = (0.422205 * qqq) / b0;
var bigB = 1.0 - (b1 + b2 + b3);
// horizontal
for (var c = 0; c < 3; c++) {
for (var y = 0; y < height; y++) {
// forward
var index = y * width4 + c;
var indexLast = y * width4 + ((width - 1) << 2) + c;
var pixel = data[index];
var ppixel = pixel;
var pppixel = ppixel;
var ppppixel = pppixel;
for (; index <= indexLast; index += 4) {
pixel = bigB * data[index] + b1 * ppixel + b2 * pppixel + b3 * ppppixel;
data[index] = pixel;
ppppixel = pppixel;
pppixel = ppixel;
ppixel = pixel;
}
// backward
index = y * width4 + ((width - 1) << 2) + c;
indexLast = y * width4 + c;
pixel = data[index];
ppixel = pixel;
pppixel = ppixel;
ppppixel = pppixel;
for (; index >= indexLast; index -= 4) {
pixel = bigB * data[index] + b1 * ppixel + b2 * pppixel + b3 * ppppixel;
data[index] = pixel;
ppppixel = pppixel;
pppixel = ppixel;
ppixel = pixel;
}
}
}
// vertical
for (var c = 0; c < 3; c++) {
for (var x = 0; x < width; x++) {
// forward
var index = (x << 2) + c;
var indexLast = (height - 1) * width4 + (x << 2) + c;
var pixel = data[index];
var ppixel = pixel;
var pppixel = ppixel;
var ppppixel = pppixel;
for (; index <= indexLast; index += width4) {
pixel = bigB * data[index] + b1 * ppixel + b2 * pppixel + b3 * ppppixel;
data[index] = pixel;
ppppixel = pppixel;
pppixel = ppixel;
ppixel = pixel;
}
// backward
index = (height - 1) * width4 + (x << 2) + c;
indexLast = (x << 2) + c;
pixel = data[index];
ppixel = pixel;
pppixel = ppixel;
ppppixel = pppixel;
for (; index >= indexLast; index -= width4) {
pixel = bigB * data[index] + b1 * ppixel + b2 * pppixel + b3 * ppppixel;
data[index] = pixel;
ppppixel = pppixel;
pppixel = ppixel;
ppixel = pixel;
}
}
}
return(pixels);
}
}
function initializeBuffer(c, img) {
// clean up the buffer between iterations
c.clearRect(0, 0, c.width, c.height);
// make sure we're drawing something
if (img.width > 0 && img.height > 0) {
// console.log(img.width, img.height, c.width, c.height);
try {
// draw the image to buffer and load its pixels into an array
// (remove the last two arguments on this function if you choose not to
// respect width/height attributes and want the original image dimensions instead)
c.drawImage(img, 0, 0, img.width , img.height);
return(c.getImageData(0, 0, c.width, c.height));
} catch(err) {
// it's kinda strange, I'm explicitly checking for width/height above, but some attempts
// throw an INDEX_SIZE_ERR as if I'm trying to draw a 0x0 or negative image, as per
// http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#images
//
// AND YET, if I simply catch the exception, the filters render anyway and all is well.
// there must be a reason for this, I just don't know what it is yet.
//
console.log("exception: " + err);
}
}
}
// parse a shorthand or longhand hex string, with or without the leading '#', into something usable
function createColor(src) {
// strip the leading #, if it exists
src = src.replace(/^#/, '');
// if it's shorthand, expand the values
if (src.length == 3) {
src = src.replace(/(.)/g, '$1$1');
}
return(src);
}
// find a specified distance between two colours
function findColorDifference(dif, dest, src) {
return(dif * dest + (1 - dif) * src);
}
// throw three new RGB values into the pixels object at a specific spot
function setRGB(data, index, r, g, b) {
data[index] = r;
data[index + 1] = g;
data[index + 2] = b;
return data;
}