画布 - 图像不透明度循环(淡入)

时间:2014-10-31 04:08:17

标签: javascript html5 canvas

人。这里有一些应该没问题的代码,虽然它不起作用......嘿......非常典型=)

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/

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

1 个答案:

答案 0 :(得分:3)

您需要一个循环才能在各种不透明度级别重绘图像。对于循环,您需要一些不会阻止UI以及每次监视器更新时刷新的内容,因此请求救援框架。

以下是解决此问题的一种方法:

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

希望这有帮助!