我正在尝试使用HTML5 canvas将图像转换为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>
最佳答案
就目前而言,您只是在更改oRedPixel,oGreenPixel和oBluePixel的值,但实际的oPixelArray
保持不变。
尝试直接更改数组值
oPixelArray[iCount] = oGreyValue;
oPixelArray[iCount+1] = oGreyValue;
oPixelArray[iCount+2] = oGreyValue;
而且您不需要此行,因为画布没有
src
属性// oCanvas.src = oCanvas.toDataURL();
关于javascript - 鼠标悬停时的灰度,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14447707/