首页 > 解决方案 > 在画布上单独淡入项目

问题描述

我想为单个矩形设置动画。我正在尝试独立淡入矩形。我想创建 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);
}

标签: javascriptanimationcanvas

解决方案


您只需要一个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);
}
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;"></canvas>


推荐阅读