-
Notifications
You must be signed in to change notification settings - Fork 1
/
Making Image Filters with Canvas - HTML5 Rocks.html
1131 lines (909 loc) · 36.3 KB
/
Making Image Filters with Canvas - HTML5 Rocks.html
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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en" dir="ltr" itemscope itemtype="http://schema.org/Article">
<head>
<meta charset="utf-8">
<meta property="twitter:account_id" content="1593210261" />
<!-- Copyright (c) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: Ilmari Heikkinen <[email protected]>
*
*
*
-->
<title>Making Image Filters with Canvas - HTML5 Rocks</title>
<meta name="description" content="A quick guide to writing custom image filters with &lt;canvas&gt;.">
<meta name="keywords" content="html5,html 5,html5 demos,html5 examples,javascript,css3,notifications,geolocation,web workers,apppcache,file api,filereader,indexeddb,offline,audio,video,drag and drop,chrome,sse,mobile">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
<meta name="theme-color" content="#f04530">
<link rel="shortcut icon" href="/favicon.ico">
<link rel="alternate" type="application/rss+xml" title="HTML5 Rocks RSS" href="http://feeds.feedburner.com/html5rocks">
<meta name="google-site-verification" content="E1HOIDkksrWY5npenL8FeQhKn4Ujctd75iO2lfufSyA" />
<meta itemprop="name" content="Image Filters with Canvas - HTML5 Rocks">
<meta itemprop="description" content="A quick guide to writing custom image filters with &lt;canvas&gt;.">
<meta itemprop="image" content="http://www.html5rocks.com/static/images/html5rocks-logo-wings.png">
<meta name="twitter:card" content="summary">
<meta name="twitter:site" content="@ChromiumDev">
<meta name="twitter:creator" content="@ilmarihei">
<meta property="og:type" content="article">
<meta property="og:title" content="Image Filters with Canvas - HTML5 Rocks">
<meta property="og:url" content="http://www.html5rocks.com/en/tutorials/canvas/imagefilters/">
<meta property="og:description" content="A quick guide to writing custom image filters with &lt;canvas&gt;.">
<meta property="og:image" content="http://www.html5rocks.com/static/images/profiles/ilmari.png">
<meta property="og:site_name" content="HTML5 Rocks - A resource for open web HTML5 developers">
<link rel="author" href="https://www.google.com/profiles/115293744081058969329">
<link rel="publisher" href="https://plus.google.com/+GoogleChromeDevelopers">
<link rel="stylesheet" media="all" href="/static/css/v2-combined.min.css?20131111">
<link href="//fonts.googleapis.com/css?family=Open+Sans:300,400,400italic,600,800|Source+Code+Pro" rel="stylesheet">
<link rel="apple-touch-icon" href="/static/images/identity/HTML5_Badge_64.png">
<link rel="apple-touch-icon-precomposed" href="/static/images/identity/HTML5_Badge_64.png">
<script src="/static/js/modernizr.custom.82437.js"></script>
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5-els.js"></script>
<![endif]-->
<style type="text/css">
#customMatrix input {
text-align: center;
}
</style>
</head>
<body data-href="tutorials-canvas-imagefilters" onload="" class="article tutorial">
<header class="main" id="siteheader">
<h1 id="title">
<a href="/en/" title="HTML5 Rocks">HTML5 Rocks</a>
</h1>
<a href="#sitenav" id="navtoggle">Show navigation</a>
<a id="toctoggle" href="#toc">Table of Contents</a>
<nav id="sitenav">
<ul>
<li id="home_menu"><a href="/en/" class="home">Home</a></li>
<li id="tutorials_menu"><a href="/en/tutorials/?page=1" class="tutorials">Tutorials</a></li>
<li id="updates_menu"><a href="http://updates.html5rocks.com/" class="updates">Updates</a></li>
</ul>
</nav>
<nav class="toc" id="toc">
<h1>Table of Contents</h1>
<ul><li><a href='#toc-introduction'>Introduction</a></li><li><a href='#toc-setup'>Processing pixels</a></li><li><a href='#toc-simplefilters'>Running simple filters</a></li><li><a href='#toc-convolution'>Convolving images</a></li><li><a href='#toc-conclusion'>Conclusion</a></li></ul>
<h1 class="visible-title">Localizations:</h1>
<ul>
<li><a href="https://github.com/html5rocks/www.html5rocks.com/blob/master/CONTRIBUTING.md">Contribute one</a></li>
</ul>
</nav>
</header>
<div class="body-content">
<section class="title">
<section class="redirect_notification error-block" lang="de">
<p>Leider ist dieser Artikel nicht in Ihrer Sprache verfügbar, Sie wurden zur englischen Version weitergeleitet.</p>
</section>
<section class="title-text container">
<h1>Image Filters with Canvas</h1>
<a href="/en/" class="watermark">HTML5 Rocks</a>
</section>
</section>
<article class="content-wrapper">
<section class="container">
<div class="article-meta" id="article-meta">
<nav class="toc">
<h1>Table of Contents</h1>
<ul><li><a href='#toc-introduction'>Introduction</a></li><li><a href='#toc-setup'>Processing pixels</a></li><li><a href='#toc-simplefilters'>Running simple filters</a></li><li><a href='#toc-convolution'>Convolving images</a></li><li><a href='#toc-conclusion'>Conclusion</a></li></ul>
</nav>
<aside class="localizations">
<h1>Localizations</h1>
<ul>
<li><a href="https://github.com/html5rocks/www.html5rocks.com/blob/master/CONTRIBUTING.md">Contribute one</a></li>
</ul>
</aside>
</div>
<div class="content" id="article-content">
<section class="byline">
<div class="byline-content">
<section class="author-images">
<a href="/profiles/#ilmari">
<img src="/static/images/profiles/ilmari.png" itemprop="photo" alt="Ilmari Heikkinen" title="Ilmari Heikkinen">
</a>
</section>
<section class="meta">
<div class="authors">
<strong>By</strong> <a href="/profiles/#ilmari">Ilmari Heikkinen</a>
</div>
<div class="date">
<time pubdate><strong>Published:</strong> May 25th, 2011</time>
<span><strong>Comments:</strong> <a href="#disqus_thread" class="load-comments" data-disqus-identifier="http://www.html5rocks.com/tutorials/canvas/imagefilters/">0</a></span>
</div>
<div id="notcompatible" class="hidden">
Your browser may not support the functionality in this article.
</div>
</section>
<div class="clear"></div>
</div>
</section>
<section>
<h2 id="toc-introduction">Introduction</h2>
<p>
The HTML5 canvas element can be used to write image filters. What you
need to do is draw an image onto a canvas, read back the canvas pixels,
and run your filter on them. You can then write the result onto a new
canvas (or heck, just reuse the old one.)
</p>
<p>
Sounds simple? Good. Let's get cracking!
</p>
<figure>
<img id="orig" src="demo_small.png" width="600" height="337">
<figcaption>The original test image</figcaption>
</figure>
</section>
<section>
<h2 id="toc-setup">Processing pixels</h2>
<p>
First, retrieve the image pixels:
</p>
<pre class="prettyprint collapsible">
Filters = {};
Filters.getPixels = function(img) {
var c = this.getCanvas(img.width, img.height);
var ctx = c.getContext('2d');
ctx.drawImage(img);
return ctx.getImageData(0,0,c.width,c.height);
};
Filters.getCanvas = function(w,h) {
var c = document.createElement('canvas');
c.width = w;
c.height = h;
return c;
};
</pre>
<p>
Next, we need a way to filter images. How about a <code>filterImage</code>
method that takes a filter and an image and returns the filtered pixels?
</p>
<pre class="prettyprint collapsible">
Filters.filterImage = function(filter, image, var_args) {
var args = [this.getPixels(image)];
for (var i=2; i<arguments.length; i++) {
args.push(arguments[i]);
}
return filter.apply(null, args);
};
</pre>
</section>
<section>
<h2 id="toc-simplefilters">Running simple filters</h2>
<p>
Now that we have the pixel processing pipeline put together, it's time to
write some simple filters. To start off, let's convert the image to grayscale.
</p>
<pre class="prettyprint collapsible">
Filters.grayscale = function(pixels, args) {
var d = pixels.data;
for (var i=0; i<d.length; i+=4) {
var r = d[i];
var g = d[i+1];
var b = d[i+2];
// CIE luminance for the RGB
// The human eye is bad at seeing red and blue, so we de-emphasize them.
var v = 0.2126*r + 0.7152*g + 0.0722*b;
d[i] = d[i+1] = d[i+2] = v
}
return pixels;
};
</pre>
<figure>
<canvas id="grayscale" width="600" height="337"></canvas>
<button onclick="grayscale()">Grayscale the image</button>
</figure>
<p>
Adjusting brightness can be done by adding a fixed value to the
pixels:
</p>
<pre class="prettyprint collapsible">
Filters.brightness = function(pixels, adjustment) {
var d = pixels.data;
for (var i=0; i<d.length; i+=4) {
d[i] += adjustment;
d[i+1] += adjustment;
d[i+2] += adjustment;
}
return pixels;
};
</pre>
<figure>
<canvas id="brightness" width="600" height="337"></canvas>
<button onclick="brightness()">Brighten the image</button>
</figure>
<p>
Thresholding an image is also quite simple. You just compare the grayscale
value of a pixel to the threshold value and set the color based on that:
</p>
<pre class="prettyprint collapsible">
Filters.threshold = function(pixels, threshold) {
var d = pixels.data;
for (var i=0; i<d.length; i+=4) {
var r = d[i];
var g = d[i+1];
var b = d[i+2];
var v = (0.2126*r + 0.7152*g + 0.0722*b >= threshold) ? 255 : 0;
d[i] = d[i+1] = d[i+2] = v
}
return pixels;
};
</pre>
<figure>
<canvas id="threshold" width="600" height="337"></canvas>
<button onclick="threshold()">Threshold the image</button>
</figure>
</section>
<section>
<h2 id="toc-convolution">Convolving images</h2>
<p>
<a href="http://en.wikipedia.org/wiki/Convolution">Convolution filters</a> are very useful generic filters for image processing.
The basic idea is that you take the weighed sum of a
rectangle of pixels from the source image and use that as the output value.
Convolution filters can be used for blurring, sharpening, embossing,
edge detection and a whole bunch of other things.
</p>
<pre class="prettyprint collapsible">
Filters.tmpCanvas = document.createElement('canvas');
Filters.tmpCtx = Filters.tmpCanvas.getContext('2d');
Filters.createImageData = function(w,h) {
return this.tmpCtx.createImageData(w,h);
};
Filters.convolute = function(pixels, weights, opaque) {
var side = Math.round(Math.sqrt(weights.length));
var halfSide = Math.floor(side/2);
var src = pixels.data;
var sw = pixels.width;
var sh = pixels.height;
// pad output by the convolution matrix
var w = sw;
var h = sh;
var output = Filters.createImageData(w, h);
var dst = output.data;
// go through the destination image pixels
var alphaFac = opaque ? 1 : 0;
for (var y=0; y<h; y++) {
for (var x=0; x<w; x++) {
var sy = y;
var sx = x;
var dstOff = (y*w+x)*4;
// calculate the weighed sum of the source image pixels that
// fall under the convolution matrix
var r=0, g=0, b=0, a=0;
for (var cy=0; cy<side; cy++) {
for (var cx=0; cx<side; cx++) {
var scy = sy + cy - halfSide;
var scx = sx + cx - halfSide;
if (scy >= 0 && scy < sh && scx >= 0 && scx < sw) {
var srcOff = (scy*sw+scx)*4;
var wt = weights[cy*side+cx];
r += src[srcOff] * wt;
g += src[srcOff+1] * wt;
b += src[srcOff+2] * wt;
a += src[srcOff+3] * wt;
}
}
}
dst[dstOff] = r;
dst[dstOff+1] = g;
dst[dstOff+2] = b;
dst[dstOff+3] = a + alphaFac*(255-a);
}
}
return output;
};
</pre>
<p>
Here's a 3x3 sharpen filter. See how it focuses the weight on the center pixel.
To maintain the brightness of the image, the sum of the matrix values should
be one.
</p>
<pre>
Filters.filterImage(Filters.convolute, image,
[ 0, -1, 0,
-1, 5, -1,
0, -1, 0 ]
);
</pre>
<figure>
<canvas id="sharpen" width="600" height="337"></canvas>
<button onclick="sharpen()">Sharpen the image</button>
</figure>
<p>
Here's an another example of a convolution filter, the box blur. The box
blur outputs the average of the pixel values inside the convolution matrix.
The way to do that is to create a convolution matrix of size NxN where
each of the weights is 1 / (NxN). That way each of the pixels inside the
matrix contributes an equal amount to the output image and the sum of the
weights is one.
</p>
<pre>
Filters.filterImage(Filters.convolute, image,
[ 1/9, 1/9, 1/9,
1/9, 1/9, 1/9,
1/9, 1/9, 1/9 ]
);
</pre>
<figure>
<canvas id="blurC" width="600" height="337"></canvas>
<button onclick="blurC()">Blur the image</button>
</figure>
<p>
We can make more complex image filters by combining existing filters. For
example, let's write a <a href="http://en.wikipedia.org/wiki/Sobel_filter">Sobel filter</a>. A Sobel filter computes the vertical
and horizontal gradients of the image and combines the computed images to
find edges in the image.
The way we implement the Sobel filter here is by first grayscaling the image,
then taking the horizontal and vertical gradients and finally
combining the gradient images to make up the final image.
</p>
<p>
Regarding terminology, "gradient" here means the change
in pixel value at an image position. If a pixel has a left neighbour with
value 20 and a right neighbour with value 50, the horizontal gradient at
the pixel would be 30. The vertical gradient has the same idea but
uses the above and below neighbours.
</p>
<pre>
var grayscale = Filters.filterImage(Filter.grayscale, image);
// Note that ImageData values are clamped between 0 and 255, so we need
// to use a Float32Array for the gradient values because they
// range between -255 and 255.
var vertical = Filters.convoluteFloat32(grayscale,
[ -1, 0, 1,
-2, 0, 2,
-1, 0, 1 ]);
var horizontal = Filters.convoluteFloat32(grayscale,
[ -1, -2, -1,
0, 0, 0,
1, 2, 1 ]);
var final_image = Filters.createImageData(vertical.width, vertical.height);
for (var i=0; i<final_image.data.length; i+=4) {
// make the vertical gradient red
var v = Math.abs(vertical.data[i]);
final_image.data[i] = v;
// make the horizontal gradient green
var h = Math.abs(horizontal.data[i]);
final_image.data[i+1] = h;
// and mix in some blue for aesthetics
final_image.data[i+2] = (v+h)/4;
final_image.data[i+3] = 255; // opaque alpha
}
</pre>
<figure>
<canvas id="sobel" width="600" height="337"></canvas>
<button onclick="sobel()">Run a Sobel filter on the image</button>
</figure>
<p>
To cap off our journey into convolution, here's a little toy for you to play with:
A custom 3x3 convolution filter! Yay!
</p>
<figure>
<canvas id="custom" width="600" height="337"></canvas>
<div id="customMatrix">
<input type="text" value="1" size="3">
<input type="text" value="1" size="3">
<input type="text" value="1" size="3">
<br>
<input type="text" value="1" size="3">
<input type="text" value="0.7" size="3">
<input type="text" value="-1" size="3">
<br>
<input type="text" value="-1" size="3">
<input type="text" value="-1" size="3">
<input type="text" value="-1" size="3">
<br>
</div>
<button onclick="custom()">Run the above filter on the image</button>
</figure>
<p>
And there's a whole bunch of other cool convolution filters out there
just waiting for you to discover them.
For instance, try implementing a <a href="http://en.wikipedia.org/wiki/Discrete_Laplace_operator#Implementation_in_Image_Processing">Laplace filter</a>
in the convolution toy above and see what it does.
</p>
</section>
<section>
<h2 id="toc-conclusion">Conclusion</h2>
<p>
I hope this small article was useful in introducing the basic concepts
of writing image filters in JavaScript using the HTML canvas tag. I
encourage you to go and implement some more image filters, it's quite
fun!
</p>
<p>
If you need better performance from your filters, you can usually
port them to use WebGL fragment shaders to do the image processing.
With shaders, you can run most simple filters in realtime, which allows
you to use them for post-processing video and animations.
</p>
</section>
<script type="text/javascript">
Filters = {};
Filters.getPixels = function(img) {
var c,ctx;
if (img.getContext) {
c = img;
try { ctx = c.getContext('2d'); } catch(e) {}
}
if (!ctx) {
c = this.getCanvas(img.width, img.height);
ctx = c.getContext('2d');
ctx.drawImage(img, 0, 0);
}
return ctx.getImageData(0,0,c.width,c.height);
};
Filters.getCanvas = function(w,h) {
var c = document.createElement('canvas');
c.width = w;
c.height = h;
return c;
};
Filters.filterImage = function(filter, image, var_args) {
var args = [this.getPixels(image)];
for (var i=2; i<arguments.length; i++) {
args.push(arguments[i]);
}
return filter.apply(null, args);
};
Filters.grayscale = function(pixels, args) {
var d = pixels.data;
for (var i=0; i<d.length; i+=4) {
var r = d[i];
var g = d[i+1];
var b = d[i+2];
// CIE luminance for the RGB
var v = 0.2126*r + 0.7152*g + 0.0722*b;
d[i] = d[i+1] = d[i+2] = v
}
return pixels;
};
Filters.brightness = function(pixels, adjustment) {
var d = pixels.data;
for (var i=0; i<d.length; i+=4) {
d[i] += adjustment;
d[i+1] += adjustment;
d[i+2] += adjustment;
}
return pixels;
};
Filters.threshold = function(pixels, threshold) {
var d = pixels.data;
for (var i=0; i<d.length; i+=4) {
var r = d[i];
var g = d[i+1];
var b = d[i+2];
var v = (0.2126*r + 0.7152*g + 0.0722*b >= threshold) ? 255 : 0;
d[i] = d[i+1] = d[i+2] = v
}
return pixels;
};
Filters.tmpCanvas = document.createElement('canvas');
Filters.tmpCtx = Filters.tmpCanvas.getContext('2d');
Filters.createImageData = function(w,h) {
return this.tmpCtx.createImageData(w,h);
};
Filters.convolute = function(pixels, weights, opaque) {
var side = Math.round(Math.sqrt(weights.length));
var halfSide = Math.floor(side/2);
var src = pixels.data;
var sw = pixels.width;
var sh = pixels.height;
var w = sw;
var h = sh;
var output = Filters.createImageData(w, h);
var dst = output.data;
var alphaFac = opaque ? 1 : 0;
for (var y=0; y<h; y++) {
for (var x=0; x<w; x++) {
var sy = y;
var sx = x;
var dstOff = (y*w+x)*4;
var r=0, g=0, b=0, a=0;
for (var cy=0; cy<side; cy++) {
for (var cx=0; cx<side; cx++) {
var scy = Math.min(sh-1, Math.max(0, sy + cy - halfSide));
var scx = Math.min(sw-1, Math.max(0, sx + cx - halfSide));
var srcOff = (scy*sw+scx)*4;
var wt = weights[cy*side+cx];
r += src[srcOff] * wt;
g += src[srcOff+1] * wt;
b += src[srcOff+2] * wt;
a += src[srcOff+3] * wt;
}
}
dst[dstOff] = r;
dst[dstOff+1] = g;
dst[dstOff+2] = b;
dst[dstOff+3] = a + alphaFac*(255-a);
}
}
return output;
};
if (!window.Float32Array)
Float32Array = Array;
Filters.convoluteFloat32 = function(pixels, weights, opaque) {
var side = Math.round(Math.sqrt(weights.length));
var halfSide = Math.floor(side/2);
var src = pixels.data;
var sw = pixels.width;
var sh = pixels.height;
var w = sw;
var h = sh;
var output = {
width: w, height: h, data: new Float32Array(w*h*4)
};
var dst = output.data;
var alphaFac = opaque ? 1 : 0;
for (var y=0; y<h; y++) {
for (var x=0; x<w; x++) {
var sy = y;
var sx = x;
var dstOff = (y*w+x)*4;
var r=0, g=0, b=0, a=0;
for (var cy=0; cy<side; cy++) {
for (var cx=0; cx<side; cx++) {
var scy = Math.min(sh-1, Math.max(0, sy + cy - halfSide));
var scx = Math.min(sw-1, Math.max(0, sx + cx - halfSide));
var srcOff = (scy*sw+scx)*4;
var wt = weights[cy*side+cx];
r += src[srcOff] * wt;
g += src[srcOff+1] * wt;
b += src[srcOff+2] * wt;
a += src[srcOff+3] * wt;
}
}
dst[dstOff] = r;
dst[dstOff+1] = g;
dst[dstOff+2] = b;
dst[dstOff+3] = a + alphaFac*(255-a);
}
}
return output;
};
</script>
<script>
var img = document.getElementById('orig');
img.addEventListener('load', function() {
var canvases = document.getElementsByTagName('canvas');
for (var i=0; i<canvases.length; i++) {
var c = canvases[i];
c.parentNode.insertBefore(img.cloneNode(true), c);
c.style.display = 'none';
}
function runFilter(id, filter, arg1, arg2, arg3) {
var c = document.getElementById(id);
var s = c.previousSibling.style;
var b = c.parentNode.getElementsByTagName('button')[0];
if (b.originalText == null) {
b.originalText = b.textContent;
}
if (s.display == 'none') {
s.display = 'inline';
c.style.display = 'none';
b.textContent = b.originalText;
} else {
var idata = Filters.filterImage(filter, img, arg1, arg2, arg3);
c.width = idata.width;
c.height = idata.height;
var ctx = c.getContext('2d');
ctx.putImageData(idata, 0, 0);
s.display = 'none';
c.style.display = 'inline';
b.textContent = 'Restore original image';
}
}
grayscale = function() {
runFilter('grayscale', Filters.grayscale);
}
brightness = function() {
runFilter('brightness', Filters.brightness, 40);
}
threshold = function() {
runFilter('threshold', Filters.threshold, 128);
}
sharpen = function() {
runFilter('sharpen', Filters.convolute,
[ 0, -1, 0,
-1, 5, -1,
0, -1, 0]);
}
blurC = function() {
runFilter('blurC', Filters.convolute,
[ 1/9, 1/9, 1/9,
1/9, 1/9, 1/9,
1/9, 1/9, 1/9 ]);
}
sobel = function() {
runFilter('sobel', function(px) {
px = Filters.grayscale(px);
var vertical = Filters.convoluteFloat32(px,
[-1,-2,-1,
0, 0, 0,
1, 2, 1]);
var horizontal = Filters.convoluteFloat32(px,
[-1,0,1,
-2,0,2,
-1,0,1]);
var id = Filters.createImageData(vertical.width, vertical.height);
for (var i=0; i<id.data.length; i+=4) {
var v = Math.abs(vertical.data[i]);
id.data[i] = v;
var h = Math.abs(horizontal.data[i]);
id.data[i+1] = h
id.data[i+2] = (v+h)/4;
id.data[i+3] = 255;
}
return id;
});
}
custom = function() {
var inputs = document.getElementById('customMatrix').getElementsByTagName('input');
var arr = [];
for (var i=0; i<inputs.length; i++) {
arr.push(parseFloat(inputs[i].value));
}
runFilter('custom', Filters.convolute, arr, true);
}
}, false);
</script>
</div>
</section>
</article>
<section class="disqus pattern-bg-lighter">
<div id="disqus" class="container">
<h2>Comments</h2>
<div id="disqus_thread">
<a href="#disqus_thread" class="load-comments" data-disqus-identifier="http://www.html5rocks.com/tutorials/canvas/imagefilters/">0</a>
</div>
</div>
<noscript>
<p class="center">
<strong>
<a href="http://disqus.com/?ref_noscript">Please enable JavaScript to view the comments powered by Disqus.</a>
</strong>
</p>
</noscript>
<script>
var disqus_shortname = 'html5rocks';
var disqus_identifier = 'http://www.html5rocks.com/tutorials/canvas/imagefilters/';
var disqus_url = 'http://www.html5rocks.com/tutorials/canvas/imagefilters/';
var disqus_developer = 0;
var disqus_config = function () {
var funky_language_code_mapping = {
'de': 'de_inf',
'es': 'es_ES',
'pt': 'pt_EU',
'sr': 'sr_CYRL',
'sv': 'sv_SE',
'zh': 'zh_HANT'
};
this.language = funky_language_code_mapping['en'] ||
'en';
this.callbacks.onReady = [ function () {
try {
ga('send', 'event', 'View comments');
} catch(err){}
} ];
this.callbacks.onNewComment = [ function (comment) {
try {
ga('send', 'event', 'Commented');
} catch(err){}
} ];
};
window.addEventListener('load', function(e) {
var c = document.createElement('script');
c.type = 'text/javascript';
c.src = 'http://' + disqus_shortname + '.disqus.com/count.js';
c.async = true;
var s = document.getElementsByTagName('script')[0], sp = s.parentNode;
sp.insertBefore(c, s);
if (window.location.hash === '#disqus_thread')
loadComments();
}, false);
var disqus_loaded = false;
function loadComments() {
if (disqus_loaded)
return;
disqus_loaded = true;
ga('send', 'event', 'Interactions', 'Comments', 'Comments Loaded');
var s = document.getElementsByTagName('script')[0], sp = s.parentNode;
var dsq = document.createElement('script');
dsq.type = 'text/javascript';
dsq.async = true;
var disqusContainer = document.getElementById('disqus');
disqusContainer.classList.add('active');
dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
sp.insertBefore(dsq, s);
}
function outgoing(url) {
try {
ga('send', 'event', 'Outbound Links' , url);
} catch(err){}
}
// Open external links (also that don't have a target defined) in a new tab.
var externLinks = document.querySelectorAll('article.tutorial a[href^="http"]:not([target])');
for(var i = 0, a; a = externLinks[i]; ++i) {
a.target = '_blank';
a.addEventListener('click', new Function('outgoing(' + '"' + a.href.replace(/.*?:\/\//g, "") + '"' + ');'));
}
var loadCommentsButtons = document.querySelectorAll('.load-comments');
for(var l = 0; l < loadCommentsButtons.length; l++)
loadCommentsButtons[l].addEventListener('click', loadComments);
</script>
</section>
<footer>
<div class="container">
<h1>Next steps</h2>
<aside class="panel share">
<h2>Share</h2>
<a href="https://twitter.com/share?url=http://www.html5rocks.com/tutorials/canvas/imagefilters/&text=Image Filters with Canvas&lang=en&via=ChromiumDev&related=ChromiumDev" class="twitter" target="_blank">Twitter</a>
<a href="https://www.facebook.com/sharer/sharer.php?u=http://www.html5rocks.com/tutorials/canvas/imagefilters/" class="facebook" target="_blank">Facebook</a>
<a href="https://plus.google.com/share?url=http://www.html5rocks.com/tutorials/canvas/imagefilters/" class="gplus" onclick="javascript:window.open(this.href, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600');return false;">Google+</a>
</aside>
<aside class="panel rss">
<h2>Subscribe</h2>
<p>Enjoyed this article? Grab the <a href="http://feeds.feedburner.com/html5rocks">RSS feed</a> and stay up-to-date.</p>
</aside>
<p class="licensing">
Except as otherwise <a href="http://code.google.com/policies.html#restrictions">noted</a>, the content of this page is licensed under the <a href="http://creativecommons.org/licenses/by/3.0/">Creative Commons Attribution 3.0 License</a>, and code samples are licensed under the <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache 2.0 License</a>.
</p>
</div>
</footer>
<script>
window.isCompatible = function() {
return !!Modernizr.canvas
};
if (isCompatible() === false) {
document.getElementById('notcompatible').className = '';
}
function _prettyPrint() {
if (typeof customPrettyPrintLanguage != 'undefined') {
customPrettyPrintLanguage();
}
prettyPrint();
}
</script>
<script async src="/static/js/prettify.min.js" onload="_prettyPrint()"></script>
<!-- Google Tag Manager -->
<noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-XXXX"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-MB3LRF');</script>
<!-- End Google Tag Manager -->
</div>
<script>
(function() {
// Kill feedburner and marketing tracking arguments, but let them register
// before we do it.
setTimeout(function() {
if (/^\?utm_/.test(document.location.search) &&
window.history.replaceState) {
window.history.replaceState(
{}, '', document.location.href.replace(/\?utm_.*/, ''));
}
}, 2000);
var siteHeader = document.getElementById('siteheader');
var navToggle = document.getElementById('navtoggle');
var siteNav = document.getElementById('sitenav');
function toggle(target, forceActive) {
if (typeof toc !== 'undefined') {
// Switch off whichever one is not the
// current target
if (target === toc)
siteNav.classList.remove('active');
else
toc.classList.remove('active');