Aravinth
Aravinth

Reputation: 139

How to use JavaScript to show a grayscale version of an image on mouseover in Firefox?

I'm trying to convert a colour image to grayscale on mouseover using JavaScript in Firefox. So far I have this:

<!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>

Which produces this error:

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

How do I correct it?

Upvotes: 1

Views: 688

Answers (2)

Dany Maor
Dany Maor

Reputation: 2411

you can use jfunc funcions - http://jfunc.com/jFunc-functions.aspx - use the function "jFunc_CanvasFilterGrayscale" and call the function onmouseover event.

Upvotes: 0

ShawnDaGeek
ShawnDaGeek

Reputation: 4150

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

It is pretty strait forward and tested good for me in all browsers.

Upvotes: 2

Related Questions