Created
November 27, 2012 15:47
-
-
Save yarcowang/4154963 to your computer and use it in GitHub Desktop.
RGB转灰度
This file contains hidden or 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
/** | |
原始 = rgba(255,0,0,.5) + rgba(0,255,0,.5): <br /> | |
<canvas id="item0" width="120" height="120"> | |
您的浏览器不支持html5 | |
</canvas> | |
<br /> | |
灰度:<br /> | |
<canvas id="item1" width="360" height="120"> | |
您的浏览器不支持html5 | |
</canvas> | |
**/ | |
var item0 = document.getElementById('item0'); | |
var item1 = document.getElementById('item1') | |
if (item0.getContext) { | |
var c = item0.getContext('2d'); | |
c.fillStyle = 'rgba(255,0,0,.5)'; | |
c.fillRect(20, 20, 80, 80); | |
c.fillStyle = 'rgba(0,255,0,.5)'; | |
c.fillRect(40, 40, 80, 80); | |
// 公式: Gray = R*0.299 + G*0.587 + B*0.114 | |
// 经验公式: | |
// Gray = (R*1 + G*2 + B*1) >> 2 | |
// Gray = (R*19595 + G*38469 + B*7472) >> 16 | |
// try try... | |
// Gray = (R << 5 + G << 10 + B << 4) >> 7 | |
var methods = [function(r, g, b){ | |
return (r + (g << 1) + b) >> 2; | |
}, function(r, g, b) { | |
return (r * 19595 + g * 38469 + b * 7472) >> 16; | |
}, function(r, g, b) { | |
return ((r << 5) + (g << 6) + (b << 3)) >> 7; | |
}]; | |
var c = item1.getContext('2d'); | |
var g; | |
for(i = 0; i < methods.length; i++) | |
{ | |
g = methods[i](255, 0, 0); | |
c.fillStyle = 'rgba(' + g + ',' + g + ',' + g + ',.5)'; | |
c.fillRect(20 + i * 120, 20, 80, 80); | |
g = methods[i](0, 255, 0); | |
c.fillStyle = 'rgba(' + g + ',' + g + ',' + g + ',.5)'; | |
c.fillRect(40 + i * 120, 40, 80, 80); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment