简体   繁体   中英

Slowly fade away image on canvas

I used the Draw Worm and made some changes and the result was this , but I have a problem to solve. I want to make the lines that have been there a long time to slowly fade away into darkness. I made this code:

function fadeOut() {
    context.fillStyle = "rgba(0, 0, 0, 1)";
    context.fillRect(0, 0, canvas.width, canvas.height);
    setTimeout(fadeOut,10000);
}
fadeOut();

The problem is that the lines are disappearing too quickly, instead I wanted to obtain a gradual fade out, or more slowly.

That should be easy. The problem is that rgba(0, 0, 0, 1) means fully opaque black. You will probably want to try some semitransparent color. For example:

function fadeOut() {
    context.fillStyle = "rgba(0, 0, 0, 0.05)";
    context.fillRect(0, 0, canvas.width, canvas.height);
    setTimeout(fadeOut,1000);
}
fadeOut();

I also recommend using requestAnimationFrame instead of setTimeout . I made a fiddle of your code, look how much nicer it is with fast animation: https://jsfiddle.net/Darker/mwj60hq4/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM