The magic of canvas and the magic of canvas
Canvas has a magic method, getImageData. It can obtain and change the color values of no pixel in the image within the canvas.
If you have various filter algorithms. You can use canvas to convert the image filter to a function similar to meitu xiuxiu.
Usage:
1: import the image to the canvas first.
2: var canvasData = context. getImageData (0, 0, canvas. width, canvas. height); // obtain the information of each pixel in the image and obtain an array. Note that the obtained information is not a two-dimensional array such as [r, g, B, B, a], but [r, g, B,, a single array such as r, g, B, a] In the rgba order.
3: This step begins to change the rgba of each pixel. Here we will briefly introduce the algorithm and implementation steps of the grayscale effect.
function gray(canvasData){for ( var x = 0; x < canvasData.width; x++) { for ( var y = 0; y < canvasData.height; y++) { // Index of the pixel in the array var idx = (x + y * canvasData.width) * 4; var r = canvasData.data[idx + 0]; var g = canvasData.data[idx + 1]; var b = canvasData.data[idx + 2]; var gray = .299 * r + .587 * g + .114 * b; // assign gray scale value canvasData.data[idx + 0] = gray; // Red channel canvasData.data[idx + 1] = gray; // Green channel canvasData.data[idx + 2] = gray; // Blue channel canvasData.data[idx + 3] = 255; // Alpha channel // add black border if(x < 8 || y < 8 || x > (canvasData.width - 8) || y > (canvasData.height - 8)) { canvasData.data[idx + 0] = 0; canvasData.data[idx + 1] = 0; canvasData.data[idx + 2] = 0; } }}return canvasData;}
4: context. putImageData (canvasData, 0, 0); // after processing the pixel color value, remember to repaint the canvas
These codes are the code that converts an image into a black/white image. The specific effect depends on the number of filter algorithms you have mastered.
The above is all the content of this article. I hope this article will help you in your study or work. I also hope to provide more support to the customer's home!