Skip to content

Instantly share code, notes, and snippets.

@JSoon
Last active July 19, 2018 07:46
Show Gist options
  • Save JSoon/124fa9677de8f53f9788a8f3287e5364 to your computer and use it in GitHub Desktop.
Save JSoon/124fa9677de8f53f9788a8f3287e5364 to your computer and use it in GitHub Desktop.
【canvas】将彩色图片转换为灰度图片
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>colorToGrayscale</title>
</head>
<body>
<canvas id="J_MyCanvas"></canvas>
<script>
var myPic = new Image();
var myPicUrl = './color-to-grayscale.png';
myPic.onload = function () {
drawMyPic(this);
};
myPic.src = myPicUrl;
function drawMyPic(imgEle) {
var width = imgEle.width;
var height = imgEle.height;
var offsetX = 0;
var offsetY = 0;
var myCanvas = document.getElementById('J_MyCanvas');
var myCanvasCtx = myCanvas.getContext('2d');
myCanvas.width = width;
myCanvas.height = height;
myCanvasCtx.drawImage(imgEle, offsetX, offsetY, width, height);
// 注意:getImageData方法需要读取同源下的图片资源,否则会浏览器抛出一个安全异常
var imgData = myCanvasCtx.getImageData(offsetX, offsetY, width, height);
for (var i = 0; i < imgData.data.length; i += 4) {
var grayColor = colorToGrayscale({
r: imgData.data[i],
g: imgData.data[i + 1],
b: imgData.data[i + 2]
});
imgData.data[i] = grayColor;
imgData.data[i + 1] = grayColor;
imgData.data[i + 2] = grayColor;
imgData.data[i + 3] = 255;
}
myCanvasCtx.putImageData(imgData, offsetX, offsetY);
}
function colorToGrayscale(rgba) {
var R = rgba.r;
var G = rgba.g;
var B = rgba.b;
var A = rgba.a;
// 灰度公式
// https://stackoverflow.com/questions/596216/formula-to-determine-brightness-of-rgb-color
var luminanceStd = 0.2126 * R + 0.7152 * G + 0.0722 * B;
var luminanceOpt1 = 0.299 * R + 0.587 * G + 0.114 * B;
var luminanceOpt2 = Math.sqrt(0.299 * Math.pow(R, 2) + 0.587 * Math.pow(G, 2) + 0.114 * Math.pow(B, 2));
var grayColor = luminanceStd;
return grayColor;
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment