复制代码代码如下: var image = document.getElementById("imageSource");
将得到的图像绘制在Canvas对象中的代码如下:
复制代码代码如下: context.drawImage(image, 0, 0);
从Canvas对象中获取图像像素数据的代码如下:
复制代码代码如下: var canvasData = context.getImageData(0, 0, canvas.width, canvas.height);
读取像素值与实现灰度计算的代码如下:
复制代码代码如下: 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]; // calculate gray scale value 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; } } }
其中计算灰度公式为 gray color = 0.299 red color + 0.578 green color + 0.114 * blue color 读取出来的像素值顺序为RGBA 分别代表red color, green color, blue color, alpha channel