Skip to content Skip to sidebar Skip to footer

Fading A Loaded Image Into Canvas With Drawimage

This question about crossfading images already gave an answer to the crossfading solution in Canvas. I am trying to do the same thing, only difference is that i am trying to fade i

Solution 1:

Yep, you need to give your images time to load.

But also, jQuery cannot do fadeIn/fadeout on a canvas element so you will have to do that manually.

Demo: http://jsfiddle.net/m1erickson/zw9S4/

Code:

<!doctype html><html><head><linktype="text/css"media="all"href="css/reset.css" /><!-- reset css --><scripttype="text/javascript"src="http://code.jquery.com/jquery.min.js"></script><style>body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style><script>
$(function(){

$("#fade").hide();

var imageURLs=[];  // put the paths to your images herevar imagesOK=0;
var imgs=[];
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-1.jpg");
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-2.jpg");
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-3.jpg");
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-4.jpg");
loadAllImages();
//functionloadAllImages(){
    for (var i=0; i<imageURLs.length; i++) {
        var img = newImage();
        imgs.push(img);
        img.onload = function(){ 
            imagesOK++; 
            if (imagesOK>=imageURLs.length ) {
                $("#fade").show();
                ctx.drawImage(imgs[0],0,0);
            }
        };
        img.onerror=function(){alert("image load failed");} 
        img.crossOrigin="anonymous";
        img.src = imageURLs[i];
    }      
}


    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    var fadeOutIndex=imgs.length-1;
    var fadeInIndex=0;
    var fadePct=0;

    functionanimateFade(){
        if(fadePct>100){return;}
        requestAnimationFrame(animateFade);
        ctx.clearRect(0,0,canvas.width,canvas.height);
        draw(imgs[fadeInIndex],fadePct/100);
        draw(imgs[fadeOutIndex],(1-fadePct/100));
        fadePct++;
    }

    functiondraw(img,opacity){
        ctx.save();
        ctx.globalAlpha=opacity;
        ctx.drawImage(img,0,0);
        ctx.restore();
    }

    $("#fade").click(function(){
        fadePct=0;
        if(++fadeOutIndex == imgs.length){fadeOutIndex=0;}
        if(++fadeInIndex == imgs.length){fadeInIndex=0;}
        animateFade();
    });

}); // end $(function(){});</script></head><body><buttonid="fade">Fade to next Image</button><br><canvasid="canvas"width=204height=204></canvas><br></body></html>

Post a Comment for "Fading A Loaded Image Into Canvas With Drawimage"