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

The magical usage of canvas

PHP中文网
PHP中文网Original
2016-05-16 19:19:171113browse

Canvas has a magical method called 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 Xiu Xiu.

How to use:

1: First import the image 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 the codes to convert the image into a black and white effect. The specific effect you can achieve depends on the filter algorithm you master. How many are there.


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