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. &NBSP
The first parameter of the function is the of the ImageData object on canvas;
The second parameter is the array corresponding to the passed-in matrix, if it is the following matrix
a b c
d e f
G h i
The second argument passed should be [a,b,c,d,e,f,g,h,i]
and the third argument is the divisor factor. &NBSP
The fourth argument is an offset.
//Compute convolution matrix functions function Convolutionmatrix (input, matrix, divisor, offset) {//Create an output of 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 finally set to 255 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;
I only wrote a 3-order convolution matrix here. If you feel that you are not high enough to achieve a 5-step.