The canvas element in HTML 5 is quite powerful, using his Getimagedata method to directly bitmap the loaded image. But directly to the bitmap operation is more troublesome, if the use of convolution matrix this tool, you can through a few simple parameters to achieve complex results.
The convolution of the so-called matrix, as shown in the following figure, when the value in the red box is computed, the 8 digits in the surrounding green box are first extracted, then the corresponding position in the applied matrix is multiplied, then the product is added together to get the final value.
For example, 42 of the above figure is:
(40*0)+(42*1)+(46*0)
+ (46*0)+(50*0)+(55*0)
+ (52*0)+(56*0)+(58*0)
= 42
This is the convolution. Then, the so-called convolution operation of the image, refers to the image of each point of the pixel value, using this matrix to operate, to get a new value.
Like the picture below.
Use the matrix below
-6-3 0
-3-1 3
0 3 6
The relief effect will be immediately available.
Then, in order to be more convenient, the final value is usually divided by a factor plus an offset.
such as the following matrix.
0 0 0
0 1 0
0 0 0
This matrix (in fact the matrix itself does not do anything to the image), and then set the coefficient of 1, offset to 255, you can achieve the inverse color effect, it is quite magical.
To simplify the operation, I wrote a simple function to manipulate the image data.
The first parameter of the function is the ImageData object on the canvas
The second argument is an array of incoming matrices, if the matrix is the following
A b C
D E F
G h I
Then the second argument passed should be [a,b,c,d,e,f,g,h,i]
The third parameter is the divisor factor.
The fourth parameter is the offset.
The code is as follows |
Copy Code |
A function to compute the convolution matrix function Convolutionmatrix (input, matrix, divisor, offset) { Create an output ImageData object var output = document.createelement ("Canvas") . GetContext (' 2d '). Createimagedata (input);
var w = input.width, h = input.height; var ID = input.data, OD = Output.data; var m = matrix;
To operate on the RGB of an internal point other than the edge point, the transparency is set to 255 at the end for (var y = 1; y < h-1; y + = 1) { for (var x = 1; x < w-1 x + + 1) { for (var c = 0; c < 3; C + + 1) { var i = (y*w + x) *4 + C; Od[i] = offset + (M[0]*id[i-w*4-4] + m[1]*id[i-w*4] + m[2]*id[i-w*4+4] + m[3]*id[i-4] + m[4]*id[i] + m[5]*id[i+4] + m[6]*id[i+w*4-4] + m[7]*id[i+w*4] + m[8]*id[i+w*4+4] /divisor; } od[(y*w + x) *4 + 3] = 255; Set transparency } } return output; } |