img
canvas
<img id="myImg" src=""/>
canvas<canvas height="200" id="myCanvas" width="200">
不支援Canvas。
</canvas>
<input id="myBtn" type="button" value="轉換灰階"/>
<script type="text/javascript">
(function(){
var canvas,context,img,btn;
var init = function(){
canvas = document.getElementById('myCanvas');
context = canvas.getContext('2d');
btn = document.getElementById('myBtn');
img = document.getElementById('myImg');
img.addEventListener('load' ,loadHandler , false);
};
var loadHandler = function(e){
btn.addEventListener('click' , converterToGray,false);
};
var converterToGray = function(e){
context.drawImage(img , 0, 0);
var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
var data = imgData.data;
var dataSize = data.length;
// console.log(imgData); is data: Uint8ClampedArray[160000]
for (var i = 0; i < dataSize ; i=i+4) {
var r = data[i] ;
var g = data[i + 1];
var b = data[i + 2];
//灰階主要計算公式
data[i] = (r * 0.272) + (g * 0.534) + (b * 0.131);
data[i + 1] = (r * 0.349) + (g * 0.686) + (b * 0.168);
data[i + 2] = (r * 0.393) + (g * 0.769) + (b * 0.189);
}
context.putImageData(imgData, 0, 0);
};
init();
}());
</script>