Magic Usage of canvas

  • 2021-07-16 01:15:47
  • OfStack

canvas has a magic method getImageData this thing. It can obtain the color value of no 1 pixel of the image within canvas, and it can be changed.

If you have a variety of filter algorithms. Then canvas can be used to realize the filter conversion of pictures, which can be made into functions similar to Mito Xiu Xiu.

Usage:

1: First import the picture into the canvas.

2: var canvasData = context. getImageData (0, 0, canvas. width, canvas. height); //Use this to get the information of each pixel of the picture and get an array. Note that instead of a 2-dimensional array of [[r, g, b, a], [r, g, b, a]], the resulting information is a single array of [r, g, b, a, r, g, b, a] arranged in the order of rgba.

3: This step is to start changing the rgba of each pixel. This paper briefly introduces the algorithm and implementation steps of gray effect under 1.


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 values, remember to redraw the canvas with this sentence

These code is the image into black-and-white effect of the code, how much effect can be achieved depends on how much you master the filter algorithm.


Related articles: