2014-10-31 66 views
1

伙计。这里是一个位的代码应该是好的,但它不工作...嘿...很典型=)画布 - 图像不透明环(淡入)

function xxx() { 

    var txtCanvas = document.getElementById('text'); 
    var textOne = txtCanvas.getContext('2d'); 
    var alpha = 0.5; 
    textOne.globalAlpha = alpha; 
    // loading image 
    var img = new Image(); 
    img.src = "http://tvangeste.com/gallery/selani/tv4_2.jpg" 
    img.onload = function() { 
     textOne.drawImage(img, 0, 0); 

    } 
    //end of image loader 

    if (alpha < 1) 
    { 
     alpha += 0.1; 

    } 



}  
requestAnimationFrame(xxx); 

这是小提琴展示如何不工作.. http://jsfiddle.net/gLs1owd6/

该脚本应该做一件简单的事情 - 淡入图像。 有什么建议吗?谢谢!

回答

3

您需要一个循环才能重新绘制各种不透明度级别的图像。对于一个循环,你需要一些不会阻塞用户界面以及每次更新显示器都会刷新的内容,所以requestAnimationFrame可以帮助你解决问题。

这里是去了解这一个办法:

var img = new Image(); 
img.onload = function() { 

    // when image has loaded we can use it. 
    // this is a self-invoking function used to fade in the image 
    (function loop() { 
     // we can update the property directly 
     textOne.globalAlpha += 0.01; 

     // as we have opacity involved we need to clear the canvas each time 
     textOne.clearRect(0, 0, txtCanvas.width, txtCanvas.height); 

     // redraw the image 
     textOne.drawImage(img, 0, 0); 

     // if not full opacity, loop (canvas will clamp the value for us) 
     if (textOne.globalAlpha < 1.0) { 
      requestAnimationFrame(loop);  
     } 
     else { 
      // when done, call the next step from here... 
     } 
    })(); 

} 

// set source as last step for image loading 
img.src = "http://tvangeste.com/gallery/selani/tv4_2.jpg" 

Modified fiddle

希望这有助于!

+0

我当然可以,陛下!非常感谢! – Rossitten 2014-10-31 05:30:20