Comments: We recommend that you use Chrome or Firefox to read this article. Otherwise, the sample program in this article may not be able to see the running effect.
1. Understand colors
We can see colorful images on the computer screen. In fact, these images are composed of pixels. So what is pixel? What is color? (If you ask these two questions, you must be a thinker.) A pixel corresponds to a group of consecutive binary bits in the memory, the value of each bit must be 0 or 1! In this way, this set of continuous binary bits can be combined by the 0 and 1 arrays, and each permutation and combination determines the color of this pixel. Let's take a look at the figure below.
Statement:The author reserves all rights for the original article! You are welcome to reprint it. Please indicate the author.Left BranchAnd SourceBlog
We can see that this figure describes six pixels, which are composed of 24 small boxes.
Note:: In the figureA small box represents a byteThat is, 8 binary bits.
Therefore,Each pixel consists of four bytes.. The meanings of these four bytes are also marked in the figure:
The first byte determines the red value of the pixel.
The second byte determines the green value of the pixel.
The third byte determines the blue value of the pixel.
The fourth byte determines the transparency of the pixel.
The size of each color value ranges from 0 to 255 (question: Why is it only 255 ?) , Transparency value: 0 indicates completely transparent, and 255 indicates completely transparent
In this way, we can use(255, 0, 0,255)To indicate a pure red Pixel
In the memory, it is such a 32-Bit String:11111111 00000000 00000000 11111111
Ii. Operation pixels
After learning about the essence of colors and pixels, we can perform more complex operations on the image.
However,Currently, HTML5 does not provide a method to directly operate pixels like setPixel or getPixel.But we also have a solution.
The ImageData object is used:
ImageData objectIt is used to save the pixel values of an image. It has three attributes: width, height, and data. The data attribute is a continuous array. All the pixel values of an image are actually saved in data.
The method for storing pixel values in the data attribute is exactly the same as that shown in the preceding figure:
ImageData. data [index * 4 + 0]
ImageData. data [index * 4 + 1]
ImageData. data [index * 4 + 2]
ImageData. data [index * 4 + 3]
The data array is taken out above.Four consecutive adjacent valuesThese four values representIndex + 1 pixelThe size of the red, green, blue, and transparency values.
Note::Index starts from 0. The image contains a total of width * height pixels, And the array stores a total of four values: width * height *.
The Context object has three methods to create, read, and set the ImageData object:
CreateImageData(Width, height): Create an ImageData object of the specified size (I .e., the pixel array) in the memory. The pixels in the object are black and transparent, that is, rgba)
GetImageData(X, y, width, height): returns an ImageData object that contains a pixel array of the specified region.
PutImageData(Data, x, y): draws an ImageData object to a specified area of the screen.
3. A simple image processing example
As mentioned above, we use the knowledge we know to play with image programming. Maybe one day we will play PhotoShop in Chrome.
The program looks like this:
1. Draw an image to a canvas element. In order not to cause a security error (Security_ERR: dom exception 18), I use a banner background image at the top of my blog. To run this example, you may need to change it to your own image.
2. There are four slide bars representing four GRBA components respectively.
3. Drag the slider to increase or decrease the color weight of the image.
4. If the image becomes transparent, the background of the canvas element will be displayed. I have set this background to my avatar.
Ideas: Actually, it is to use the getImageData method to retrieve the pixel array of the area you want to change, and then based on the slider and the value of the slider, to change the color weight of all pixels in that area. After processing, use the putImageData method to draw the image on the canvas.
The following code is used:
Simple Image Processing
The Code is as follows:
<Canvas id = "test1" width = "507" height = "348" style = "background-image: url (http://images.cnblogs.com/cnblogs_com/myqiao/262115/r_2204793492575248335.jpg)"> your browser does not support & lt; canvas & gt; label. Use Chrome or FireFox </canvas>
RED: <input type = "range" min = "1" max = "100" onchange = "colorChange (event, 0)"/>
Green: <input type = "range" min = "1" max = "100" onchange = "colorChange (event, 1)"/>
Blue: <input type = "range" min = "1" max = "100" onchange = "colorChange (event, 2)"/>
Transparency: <input type = "range" min = "1" max = "100" onchange = "colorChange (event, 3)"/>
<Script type = "text/javascript">
// Obtain the context object
Var canvas = document. getElementById ("test1 ");
Var ctx = canvas. getContext ("2d ");
// Width and length of the canvas
Var width = parseInt (canvas. getAttribute ("width "));
Var height = parseInt (canvas. getAttribute ("height "));
// Load the image
Var image = new Image ();
Image. onload = imageLoaded;
// Top background image
Image. src = "/skins/Valentine/images/banner2.gif ";
// The variable used to save the pixel array
Var imageData = null;
Function imageLoaded (){
// Draw an image on the canvas
Ctx. drawImage (image, 0, 0 );
// Retrieve the pixel array of the image
ImageData = ctx. getImageData (0, 0, width, height );
}
Function colorChange (event, offset ){
ImageLoaded ();
For (var y = 0; y <imageData. height; y ++ ){
For (x = 0; x <imageData. width; x ++ ){
// Index indicates the number of pixels to be processed.
Var index = y * imageData. width + x;
// One pixel occupies four bytes, that is, p is the position of the current pointer.
Var p = index * 4;
// Change the value of the current pixel offset color component. The offset value ranges from 0 to 3.
Var color = imageData. data [p + offset] * event.tar get. value/50;
// The color value is limited to [0 .. 255].
Color = Math. min (255, color );
// Save the changed color value to the array
ImageData. data [p + offset] = color
}
}
// Output to the screen
Ctx. putImageData (imageData, 0, 0 );
}
</Script>
Demo effect:
<P> <canvas style = "background-image: url ( http://images.cnblogs.com/cnblogs_com/myqiao/262115/r_2204793492575248335.jpg ) "Id =" test1 "height =" 230 "width =" 295 "> your browser does not support the & lt; canvas & gt; label, use Chrome or FireFox </canvas> </p> <p> Red: <input onchange = "colorChange (event, 0) "type =" range "max =" 100 "min =" 1 "> </p> <p> Green: <input onchange =" colorChange (event, 1) "type =" range "max =" 100 "min =" 1 "> </p> <p> Blue: <input onchange =" colorChange (event, 2) "type =" range "max =" 100 "min =" 1 "> </p> <p> Transparency: <input onchange =" colorChange (event, 3) "type =" range "max =" 100 "min =" 1 "> <script type =" text/javascript "> // obtain the context object var canvas = document. getElementById ("test1"); var ctx = canvas. getContext ("2d"); // The width and length of the canvas var width = parseInt (canvas. getAttribute ("width"); var height = parseInt (canvas. getAttribute ("height"); // load the image var Image = new image (); image. onload = imageLoaded; image. src = "/skins/Valentine/images/banner2.gif"; // variable used to save the pixel array var imageData = null; function imageLoaded () {// draw the image to the canvas ctx. drawImage (image, 0, 0); // to increase the speed, retrieve only the pixel array imageData = ctx in some areas of the image. getImageData (0, 0, width, height);} function colorChange (event, offset) {imageLoaded (); for (var y = 0; y <imageData. height; y ++) {for (x = 0; x <imageData. width; x ++) {// index indicates the number of pixels to be processed. var index = y * imageData. width + x; // a pixel occupies four bytes, that is, p is the position of the current pointer var p = index * 4; // Changes the value of the current pixel offset color component, the offset value is 0-3 var color = imageData. data [p + offset] * event.tar get. value/50; // The color value is limited to [0 .. 255] color = Math. min (255, color); // Save the changed color value back to the array imageData. data [p + offset] = color }}// output to screen ctx. putImageData (imageData, 0, 0) ;}</script> </p>
Tip: you can modify some code before running
4. Draw random color points
In this example, a random vertex is selected on the canvas and a random color value is given to it. In fact, the method used is similar to the above example, that is, the requirement is different.
The following are code and program instances:
Random color points
The Code is as follows:
<Canvas id = "test2" width = "300" height = "300" style = "background-color: black"> your browser does not support & lt; canvas & gt; label. Use Chrome or FireFox </canvas>
<Input type = "button" value = "draw random points" onclick = "interval = setInterval (randomPixel, 1);"/>
<Input type = "button" value = "stop" onclick = "clearInterval (interval);"/>
<Input type = "button" value = "clear" onclick = "clearCanvas ();"/>
<Script type = "text/javascript">
// Obtain the context object
Var canvas = document. getElementById ("test2 ");
Var ctx = canvas. getContext ("2d ");
// Width and length of the canvas
Var width = parseInt (canvas. getAttribute ("width "));
Var height = parseInt (canvas. getAttribute ("height "));
Var imageData = ctx. createImageData (width, height );
Function randomPixel (){
Var x = parseInt (Math. random () * width );
Var y = parseInt (Math. random () * height );
Var index = y * width + x;
Var p = index * 4;
ImageData. data [p + 0] = parseInt (Math. random () * 256 );
ImageData. data [p + 1] = parseInt (Math. random () * 256 );
ImageData. data [p + 2] = parseInt (Math. random () * 256 );
ImageData. data [p + 3] = parseInt (Math. random () * 256 );
Ctx. putImageData (imageData, 0, 0 );
}
Function clearCanvas (){
Ctx. clearRect (0, 0, width, height );
ImageData = ctx. createImageData (width, height );
}
</Script>
Demo effect:
<P> <canvas style = "background-color: black" id = "test2" height = "300" width = "300"> your browser does not support & lt; canvas & gt; label. Use Chrome or FireFox </canvas> </p> <input onclick = "interval = setInterval (randomPixel, 1 ); "value =" draw random points "type =" button "> <input onclick =" clearInterval (interval ); "value =" stop "type =" button "> <input onclick =" clearCanvas (); "value =" clear "type =" button "> <script type =" text/javascript "> // obtain the context object var canvas2 = document. getElementById ("test2"); var ctx2 = canvas2.getContext ("2d"); // The width and length of the canvas var wid2= parseInt (canvas2.getAttribute ("width ")); var height2 = parseInt (canvas2.getAttribute ("height"); var imageData2 = ctx2.createImageData (wid2, height2); function randomPixel () {var x = parseInt (Math. random () * wid2); var y = parseInt (Math. random () * height2); var index = y * imageData2.width + x; var p = index * 4; imageData2.data [p + 0] = parseInt (Math. random () * 256); imageData2.data [p + 1] = parseInt (Math. random () * 256); imageData2.data [p + 2] = parseInt (Math. random () * 256); imageData2.data [p + 3] = parseInt (Math. random () * 256); random (imageData2,);} function clearCanvas () {ctx2.clearRect (, wid2, height2); imageData2 = ctx2.createImageData (wid2, height2 );} </script> </p>
Tip: you can modify some code before running