是否可以为画布上显示的图像创建淡入效果?

时间:2013-04-07 00:57:38

标签: javascript jquery html5 canvas html5-canvas

我有一个图像(箭头),当用户与画布上的对象交互时显示该图像。此图像(箭头)告诉用户拖动对象的方向。是否可以为图像创建淡入效果?

这是代码

   var curvedArrow = new Image();
    curvedArrow.src = "img/curvedArrow.png";
// curvedArrow.onload = function() {
        context.drawImage(curvedArrow, 15, 45, 35, 30);
//  };

注意:我在没有onload的情况下调用drawImage(),因为如果我在onload中调用了drawImage,那么图像没有显示在画布上

1 个答案:

答案 0 :(得分:1)

src听众之后设置.onload,无论如何都会触发。

   var curvedArrow = new Image();
   curvedArrow.addEventListener('load', function() {
        context.drawImage(curvedArrow, 15, 45, 35, 30);
   });
   curvedArrow.src = "img/curvedArrow.png";

然后您可以使用间隔和globalAlpha淡化图像:

   var curvedArrow = new Image();
   curvedArrow.addEventListener('load', function() {
        context.globalAlpha = 0;
        var imgFadeInter = setInterval(function(){
           clearContext(); // a function that clears the canvas
           context.globalAlpha += 0.01;
           context.drawImage(curvedArrow, 15, 45, 35, 30);
           if(context.globalAlpha == 1){ 
               clearInterval(imgFadeInter); 
           }
        }, 16); // 16ms because jQuery says so         
   });
   curvedArrow.src = "img/curvedArrow.png";