如何在Firefox中使用JavaScript在鼠标悬停时显示图像的灰度版本?

时间:2011-08-26 07:55:00

标签: html css javascript firefox

我正在尝试使用Firefox中的JavaScript在鼠标悬停时将彩色图像转换为灰度。到目前为止,我有这个:

<!DOCTYPE html>
<html>
    <head>
        <title> New Document </title>
        <script type="text/javascript">
            window.onload = function () {
                var area = document.getElementById('area');
                alert('area:'+area);   
                var context = area.getContext('2d');
                alert('context:'+context);

                if (context) {
                    var imgd = context.getImageData(0, 0, 500, 300);
                    var pix = imgd.data;

                    for (var i = 0, n = pix.length; i < n; i += 4) {
                        var grayscale = pix[i  ] * .3 + pix[i+1] * .59 + pix[i+2] * .11;
                        pix[i]   = grayscale;   // red
                        pix[i+1] = grayscale;   // green
                        pix[i+2] = grayscale;   // blue
                    }

                    context.putImageData(imgd, 0, 0);
                }
            };
        </script>
    </head>

    <body>
    <canvas id="area" width="500" height="300">
        <img id="canvasSource" src="http://www.treehugger.com/elephant-national-heritage-animal-india.jpg" alt="Canvas Source" />
    </canvas>
    </body>
</html>

产生此错误:

Line: 9
Error: Object doesn't support this property or method

如何更正?

2 个答案:

答案 0 :(得分:2)

在非IE浏览器中

“GRAYSCALING” http://james.padolsey.com/javascript/grayscaling-in-non-ie-browsers/

这是非常好的前进,并且在所有浏览器中都对我有好处。

答案 1 :(得分:0)

你可以使用jfunc函数 - http://jfunc.com/jFunc-functions.aspx - 使用函数“jFunc_CanvasFilterGrayscale”并调用函数onmouseover事件。