0

我正在尝试使用 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>
4

1 回答 1

2

就目前而言,您只是更改了 oRedPixel、oGreenPixel 和 oBluePixel 的值,但实际值oPixelArray保持不变。

尝试直接更改数组值

oPixelArray[iCount] = oGreyValue;
oPixelArray[iCount+1] = oGreyValue;
oPixelArray[iCount+2] = oGreyValue;

而且你不需要这条线,因为画布没有src属性

// oCanvas.src = oCanvas.toDataURL();
于 2013-01-21T21:41:30.670 回答