Created
November 24, 2015 05:42
-
-
Save JoeKeikun/a031a031dbb07132f6de to your computer and use it in GitHub Desktop.
js 装换灰度图
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]; | |
var gray = Math.round(.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 | |
} | |
} | |
context.putImageData(canvasData, 0, 0); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment