使用drawImage将加载的图像淡入Canvas

时间:2014-02-03 21:10:55

标签: javascript jquery html5 canvas drawimage

关于crossfading images的这个问题已经回答了Canvas中的交叉淡入淡出解决方案。我试图做同样的事情,唯一的区别是我试图淡化运行时加载的图像。

正确加载图像但不会看到淡入淡出。由于加载的图像,这不起作用吗?感谢。

HTML

 <div id="wrapper">
     <canvas id="bg1"></canvas>
     <canvas id="bg2"></canvas>
 </div>

JS

var toggle = true;

var canvas         = document.getElementById('bg1');
    canvas.width   = $(document).width();
    canvas.height  = $(document).height();
var ctx            = canvas.getContext('2d');

var canvas2        = document.getElementById('bg2');
    canvas2.width  = $(document).width();
    canvas2.height = $(document).height();

var ctx2           = canvas2.getContext('2d');

var image = new Image();
image.src = 'download1.jpg';

var image2 = new Image();
image2.src = 'download2.jpg';

image.onload = function() {
    ctx.drawImage(image, 0, 0, 200, 100);
    ctx2.drawImage(image2, 0, 0, 200, 100);
};

$('#wrapper').click(function () {
    if (toggle)
    {
        $('#bg2').fadeIn();
        $('#bg1').fadeOut();
    }
    else
    {
        $('#bg1').fadeIn();
        $('#bg2').fadeOut();
    }

    toggle = !toggle;
});

2 个答案:

答案 0 :(得分:3)

是的,你需要给你的图像加载时间。

但是,jQuery无法在canvas元素上执行fadeIn / fadeout,因此您必须手动执行此操作。

演示:http://jsfiddle.net/m1erickson/zw9S4/

代码:

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="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 here
var 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();
//
function loadAllImages(){
    for (var i=0; i<imageURLs.length; i++) {
        var img = new Image();
        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;

    function animateFade(){
        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++;
    }

    function draw(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>
    <button id="fade">Fade to next Image</button><br>
    <canvas id="canvas" width=204 height=204></canvas><br>
</body>
</html>

答案 1 :(得分:2)

尝试直接在画布上淡入/淡出图像,而不是淡入和淡出画布元素(或者使用画布实际上没有任何点,因为您可以使用图像元素)。

首先,当然,等待图片加载:

var isBusy = false,       /// for fade loop
    count = 2;            /// number of images to load
    image = new Image();
    image2 = new Image();

/// setup load handler
image.onload = image2.onload = handleLoad;
image.src = 'download1.jpg';
image2.src = 'download2.jpg';

function handleLoad() {
    count--;
    if (count === 0) {

        /// when loaded draw a single image onto canvas
        ctx.drawImage(image, 0, 0, ctx.canvas.width, ctx.canvas.height);
    }
};

现在我们可以稍微改变点击处理程序并仅使用画布来淡化下一张图像:

$('#wrapper').click(function () {

    var img,         /// current image to fade in
        opacity = 0; /// current globalAlpha of canvas

    /// if we're in a fade exit until done    
    if (isBusy) return;
    isBusy = true;

    /// what image to use    
    img = toggle ? image2 : image;

    /// fade in
    (function fadeIn() {
        /// set alpha
        ctx.globalAlpha = opacity;

        /// draw image with current alpha
        ctx.drawImage(img, 0, 0, ctx.canvas.width, ctx.canvas.height);

        /// increase alpha to 1, then exit resetting isBusy flag
        opacity += 0.02;
        if (opacity < 1)
            requestAnimationFrame(fadeIn);
        else
            isBusy = false;
    })();

    toggle = !toggle;
});

Online demo

希望这有帮助。