Home >Web Front-end >JS Tutorial >The magical usage of canvas

The magical usage of canvas

高洛峰
高洛峰Original
2017-02-08 14:42:45987browse

Canvas has a magical method getImageData. It can obtain the color value of every pixel of the image in the canvas, and it can be changed.

If you have various filter algorithms. Then you can use canvas to realize the filter conversion of pictures, and you can create a function similar to Meitu Xiuxiu.

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 image and get an array. Note that the information obtained is not a two-dimensional array like [[r,g,b,a],[r,g,b,a]] but [r,g,b,a,r,g,b,a] Such a single array arranged in rgba order.

3: This step is to start changing the rgba of each pixel. Here is a brief introduction to 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 redraw the canvas with this sentence

These codes are to convert the image It is a code for black and white effect. The specific effect that can be achieved depends on how many filter algorithms you have mastered.

The above is the entire content of this article. I hope that the content of this article can bring some help to everyone's study or work. I also hope to support the PHP Chinese website!

For more articles related to the magical usage of canvas, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn