bleach64
bleach64

Reputation: 107

HTML 5 Grayscale filter not working

I am trying to make a simple HTML5 and JavaScript image filter for Grayscale, Negative and Blur effect. Whenever I click on the button nothing comes out on the canvas. Is there any way I can fix it? I am trying every possible way I can, but still failed. Please see my coding below:

JavaScript:

<script>

    function goClick(){
        var c = document.getElementById('myCanvas');
        var ctx = c.getContext('2d');
        var btnGrayscale = document.getElementById('btnGrayscale');
        var btnNegative = document.getElementById('btnNegative');
        var btnBlur = document.getElementById('btnBlur');


        var img = new Image();
        img.onload = function(){
            ctx.drawImage(img, 0, 0);

        ctx.putImageData(imgd, 10, 353);
        }

    //grayscale
        btnGrayscale.onclick = function() {
            clear();
        ctx.drawImage(imageObj, 0, 0);

        var imgData = ctx.getImageData(0, 0, c.width, c.height);
        var pixels = imgData.data;

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



        img.src = "image/Angelina_Jolie.jpg";

    }

HTML5:

<body>
    <img src="image/Angelina_Jolie.jpg" id="angelina"/>
    <canvas id='myCanvas' width='500' height='375' style='border:solid 1px #000000'></canvas>
    <input type="button" value="Grayscale" class="buttons" id="btnGrayscale" />
    <input type="button" value="Negative" class="buttons" id="btnNegative" /><br />
    <input type="button" value="Blur" class="buttons" id="btnBlur" /><br />
</body>

Upvotes: 0

Views: 894

Answers (1)

Karl-Johan Sj&#246;gren
Karl-Johan Sj&#246;gren

Reputation: 17522

Wow, there were a lot of errors in that code. Misspelled variables, objects that doesn't exist, etc.

I got it working for you by fixing all references to canvas (should have been c), removing blurPasses (didn't exist), changed the first putImageData to drawImage (it's an image, not a pixel array at that point) and more.

It's quite clear that you didn't write all yourself and you didn't really put any effort in learning what it does and thus why it didn't work. Have a look at the code available at the fiddle below and compare it to your old code and see what has changed, don't just copy&paste it into your project and be happy about it.

var img = new Image();
img.onload = function () {
    ctx.drawImage(img, 0, 0); // Can't use putImageData here!
}

http://jsfiddle.net/p6ume/3/

Upvotes: 2

Related Questions