Jquery grayscale

The following example is using Jquery and it should work in all browsers but only for images.

A full working demo can be downloaded from here

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

<p>Grayscale</p>

<img src="img/logo.png" class="grayscale" alt="grayscale demo" />

<br />

<p>No grayscale</p>

<img src="img/logo.png" alt="no grayscale image demo" />

<br />

<script type="text/javascript">

 

function grayscale(src){

 

var graycanvas = document.createElement("canvas");

var ctx = graycanvas .getContext("2d");

var imgObj = new Image();

imgObj.src = src;

graycanvas .width = imgObj.width;

graycanvas .height = imgObj.height;

ctx.drawImage(imgObj, 0, 0);

var canvasPixels = ctx.getImageData(0, 0, graycanvas .width, graycanvas .height);

 

for(var y = 0; y &lt; canvasPixels.height; y++){

for(var x = 0; x &lt; canvasPixels.width; x++){

 

var i = (y * 4) * canvasPixels.width + x * 4;

var average= (canvasPixels.data[i] + canvasPixels.data[i + 1] + canvasPixels.data[i + 2]) / 3;

canvasPixels.data[i] = average;

canvasPixels.data[i + 1] = average;

canvasPixels.data[i + 2] = average;

}

}

ctx.putImageData(canvasPixels, 0, 0, 0, 0, canvasPixels.width, canvasPixels.height);

return graycanvas .toDataURL();

}

 

(function($) {

$.fn.grayScale = function()

{

var elem=$(this);

var source=elem.attr("src");

elem.attr("src",grayscale(source));

}

}

)(jQuery);

 

//usage $(selector).grayScale();

$("img.grayscale").grayScale();

</script>

Newsletter

Sign up for inspiration, news and updates