我正在尝试使用 HTML5 画布在 Javascript 中将图像转换为灰度。我到底在这里做错了什么!?我知道它真的很近!
function convertToGreyscale(str)
{
// Get the Canvas
var oCanvas = document.getElementById(str);
// Get the Canvas Context
var oContext = oCanvas.getContext('2d');
// Get the height & width of the canvas
var oHeight = oCanvas.height;
var oWidth = oCanvas.width;
// Get the image data object
// getImageData(startX,startY,endX,endY)
var oImageData = oContext.getImageData(0,0,oHeight,oWidth);
// Get the actual pixel information
var oPixelArray = oImageData.data;
var iLength = oPixelArray.length;
for (var iCount = 0; iCount < iLength; iCount += 4)
{
var oRedPixel = oPixelArray[iCount];
var oGreenPixel = oPixelArray[iCount+1];
var oBluePixel = oPixelArray[iCount+2];
var oGreyValue = oRedPixel * 0.2126 + oGreenPixel * 0.7152 + oBluePixel * 0.0722;
// Set R,G & B to be the new grey value
oRedPixel = oGreyValue;
oGreenPixel = oGreyValue;
oBluePixel = oGreyValue;
}
// Set the greyscale image back on the canvas.
oContext.putImageData(oImageData,0,0);
oCanvas.src = oCanvas.toDataURL();
}
这是相关的HTML:
<canvas id="myCanvas" width="500" height="500"></canvas>
<div style="border: 1px solid black" onmouseover="convertToGreyscale('myCanvas')">Mouseover</div>