Black resized canvas not completely fading drawings to black over time

前端 未结 3 1830
北恋
北恋 2021-01-22 02:45

I have a black canvas with things being drawn inside it. I want the things drawn inside to fade to black, over time, in the order at which they are drawn (FIFO). This works if I

3条回答
  •  余生分开走
    2021-01-22 03:22

    To avoid the rounding problem you could extract the fade effect to a separate function with its own timer, using longer refresh interval and larger alpha value.

    var canvas = document.getElementById('canvas');
    var context = canvas.getContext('2d');
    context.fillRect(0, 0, 300, 150);
    
    // Comment this out and it works as intended, why?
    canvas.width = canvas.height = 300;
    
    window.draw = function () {
        context.fillStyle = 'rgba(255,255,255,1)';
        context.fillRect(
            Math.floor(Math.random() * 300),
            Math.floor(Math.random() * 300),
            2, 2);
        setTimeout('draw()', 1000 / 20);
    }
    
    window.fadeToBlack = function () {
        context.fillStyle = 'rgba(0,0,0,.1)';
        context.fillRect(0, 0, 300, 300);
        setTimeout('fadeToBlack()', 1000 / 4);    
    }
    
    draw();
    fadeToBlack();
    

    Fiddle demonstrating this: http://jsfiddle.net/6VvbQ/37/

提交回复
热议问题