-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.mask.js
74 lines (55 loc) · 1.67 KB
/
jquery.mask.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
(function($) {
$.extend($.fn, {
mask: function() {
this.each(function() {
var self = $(this),
src = self.attr('src'),
masksrc = src.replace(/(\.jpg|\.png)$/, "-mask$1");
if(!src) return;
self.hide();
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d');
var img = new Image();
img.onload = function() {
var imgmask = new Image();
imgmask.onload = function() {
canvas.width = img.width;
canvas.height = img.height;
ctx.putImageData(self.addMask(self.getPixels(img), self.getPixels(imgmask)), 0, 0);
self.replaceWith(canvas);
self.show();
};
imgmask.src = masksrc;
};
img.src = src;
});
return this;
},
addMask: function(pixels, mask_pixels) {
var img = pixels.data,
mask = mask_pixels.data,
i = 0, r, g, b;
for(i = 0; i < img.length; i+=4) {
r = mask[i];
g = mask[i+1];
b = mask[i+2];
img[i+3] = img[i+3] * ((r+g+b)/(255*3));
}
return pixels;
},
// From http://www.html5rocks.com/en/tutorials/canvas/imagefilters/
getCanvas: function(w,h) {
var c = document.createElement('canvas');
c.width = w;
c.height = h;
return c;
},
// From http://www.html5rocks.com/en/tutorials/canvas/imagefilters/
getPixels: function(img) {
var c = this.getCanvas(img.width, img.height);
var ctx = c.getContext('2d');
ctx.drawImage(img, 0, 0);
return ctx.getImageData(0,0,c.width,c.height);
}
});
})(jQuery);