【问题标题】:Fade in items individually on a canvas在画布上单独淡入项目
【发布时间】:2021-06-28 20:21:03
【问题描述】:

我想为单个矩形设置动画。我正在尝试独立淡入矩形。我想创建 FadeIn(rectangle) 和 FadeOut(Rectangle) 函数,我可以在其中传递一个矩形来淡入各个项目。

我见过https://codepen.io/mattsrinc/pen/YzPZbWw 但是,它有多个渲染循环、改变颜色等。我正在尝试只制作 FadeIn 和 FadeOut 功能。

<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;"></canvas>


var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var i = 0;
requestAnimationFrame(test);
requestAnimationFrame(test1);

function test() {
    i += 0.002;
    i = i < 0 ? 0 : i;
    ctx.globalAlpha = 1;
    ctx.fillStyle = "white";
    ctx.fillRect(20, 20, 75, 50);
    ctx.globalAlpha = i;
    ctx.fillStyle = "red";
    ctx.fillRect(20, 20, 75, 50);
    requestAnimationFrame(test);
}

function test1() {
    i += 0.002;
    i = i < 0 ? 0 : i;
    ctx.globalAlpha = 1;
    ctx.fillStyle = "white";
    ctx.fillRect(100, 60, 75, 50);
    ctx.globalAlpha = i;
    ctx.fillStyle = "blue";
    ctx.fillRect(100, 60, 75, 50);
    requestAnimationFrame(test1);
}

【问题讨论】:

    标签: javascript animation canvas


    【解决方案1】:

    您只需要一个requestAnimationFrame,使用clearRect 而不是绘制白色矩形,将 alpha 值限制在 0 和 1 之间,这样就不会出现奇怪的闪烁。

    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    var blueAlpha = 0;
    var blueSetp = 0.02; // Blue velocity
    var redAlpha = 0;
    var redStep = 0.01; // Red velocity
    
    const calmp = (value, min, max) => Math.max(min, Math.min(value, max));
    
    requestAnimationFrame(render);
    
    function render() {   
    
        // Setting Blue Alpha
        if(blueAlpha < 0 || blueAlpha > 1) 
          blueSetp = blueSetp * -1; // inverse blue
        blueAlpha += blueSetp;
        
        // Drawing Blue
        ctx.globalAlpha = calmp(blueAlpha, 0, 1);
        ctx.fillStyle = "blue";
        ctx.clearRect(100, 60, 75, 50); // Use clearRect
        ctx.fillRect(100, 60, 75, 50);
    
        // Setting Red alpha
        if(redAlpha < 0 || redAlpha > 1)
          redStep = redStep * -1; // inverse red
        redAlpha += redStep;
        
        // Drawing Red
        ctx.globalAlpha = calmp(redAlpha, 0, 1);
        ctx.fillStyle = "red";
        ctx.clearRect(20, 20, 75, 50);
        ctx.fillRect(20, 20, 75, 50);
        
        requestAnimationFrame(render);
    }
    &lt;canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;"&gt;&lt;/canvas&gt;

    【讨论】:

    • 谢谢。这很有帮助。
    猜你喜欢
    • 2016-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多