javascript - 在画布上单独淡入项目
问题描述
我想为单个矩形设置动画。我正在尝试独立淡入矩形。我想创建 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);
}
解决方案
您只需要一个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>
推荐阅读
- sql - 防止由于 SQL LEFT JOIN 行重复而导致的“过度报告”
- python - Discord.py 命令权限错误和命令参数错误无法正常工作
- python - 使用 Selenium/Chromedriver 的 Python 脚本停止工作
- node.js - TypeError:无法读取未定义反应的属性“id”
- flutter - MaterialApp.router 构造函数在重建时显示空白屏幕
- docker - Dockerfile:用 sed 替换文件内容将值替换为空
- flutter - 即使使用扩展也无法呈现列表视图构建器
- ios - 内部 UI 表视图不滚动
- node.js - Mongoose / MongoDB 在模式中具有唯一键的重复条目
- android-studio - CognitoUserSession 无效,因为 idToken 为空