Search code examples
jquerycanvaspixastic

Pixastic desaturate on load and colour on hover


I have a set of images that have to be desaturated on load and in colour on hover. I've tried this but the hover doesn't work, the desaturation on load it does though:

$(window).load(function () {
        $(".box img").pixastic("desaturate");

        $(".box img").mouseenter(function (e) {
            var self = $(this);
            Pixastic.revert(self); // make it colour
        });

        $(".box img").mouseleave(function (e) {
            // make it black n white again
            $(this).pixastic("desaturate");
        });

 });

I've seen some other posts here but none seem to work.
What am I doing wrong?


Solution

  • Working Demo

    // original image
    var img = document.getElementById("box");
    // desaturated image
    var img2 = Pixastic.process(img, "desaturate");
    
    //initial mouseover
    img2.onmouseover = function(){fix(img2)};
    
    // mouseout
    img.onmouseout = function() {
        // reassign to img2
        img2 = Pixastic.process(img, "desaturate");
        // rebind img2 mouseover
        img2.onmouseover = function(){fix(img2)};
    }
    
    // revert
    function fix(img) {
        Pixastic.revert(img);
    }
    

    There probably is a better way to do this, but basically everytime you revert, or desaturate you are replacing the img with a canvas element, or vice versa, which destroys any of the bound events. What the above does is rebind each of those events when this happens.

    The same could probably be done using jQueries .on