表达式基础
本章介绍 After Effects 表达式的基础语法,帮助您快速入门表达式开发。
什么是表达式?
Section titled “什么是表达式?”表达式是用于控制图层属性值的 JavaScript 代码片段。它们可以根据时间、其他属性或外部数据动态计算属性值。
// 声明变量var speed = 100;let amplitude = 50;const frequency = 2;// 数字var number = 42;
// 字符串var text = "Hello World";
// 布尔值var isVisible = true;
// 数组var position = [100, 200];var color = [1, 0, 0, 1]; // RGBA// 算术运算符var result = 10 + 5; // 加法var result = 10 - 5; // 减法var result = 10 * 5; // 乘法var result = 10 / 5; // 除法var result = 10 % 3; // 取模
// 比较运算符var isEqual = (a == b);var isGreater = (a > b);var isLess = (a < b);
// 逻辑运算符var result = (a && b); // 逻辑与var result = (a || b); // 逻辑或var result = !a; // 逻辑非常用全局变量
Section titled “常用全局变量”time // 当前时间 (秒)frameDuration // 帧持续时间frameRate // 帧率value // 当前属性值thisComp // 当前合成thisLayer // 当前图层thisProperty // 当前属性简单的摆动动画
Section titled “简单的摆动动画”// 在X轴上创建摆动效果var amplitude = 100; // 摆动振幅var frequency = 2; // 摆动频率
value + [Math.sin(time * frequency) * amplitude, 0];基于时间的缩放
Section titled “基于时间的缩放”// 随时间逐渐放大var startScale = 50;var endScale = 100;var duration = 2; // 动画时长 (秒)
if (time < duration) { var progress = time / duration; startScale + (endScale - startScale) * progress;} else { endScale;}// 根据时间的不同行为if (time < 1) { // 第一秒:淡入 [time * 100, time * 100];} else if (time < 3) { // 接下来2秒:稳定 [100, 100];} else { // 3秒后:淡出 var fadeTime = time - 3; [100 - fadeTime * 50, 100 - fadeTime * 50];}// 将旋转链接到另一图层的位置var targetLayer = thisComp.layer("目标图层");var distance = length(targetLayer.transform.position - thisLayer.transform.position);distance * 0.5; // 基于距离的旋转// 正弦波动画Math.sin(time * 2) * 100;
// 余弦波动画Math.cos(time * 2) * 100;
// 圆周运动var radius = 100;var centerX = 960;var centerY = 540;[ centerX + Math.cos(time) * radius, centerY + Math.sin(time) * radius];// 随机值Math.random() * 100; // 0-100的随机数
// 绝对值Math.abs(-50); // 返回 50
// 幂Math.pow(2, 3); // 2的3次方 = 8
// 平方根Math.sqrt(16); // 返回 41. 使用有意义的变量名
Section titled “1. 使用有意义的变量名”// 好var rotationSpeed = 45;var bounceAmplitude = 50;
// 避免var a = 45;var b = 50;2. 为您的代码添加注释
Section titled “2. 为您的代码添加注释”// 根据时间计算反弹效果var bounceFreq = 3; // 每秒反弹次数var bounceAmp = 20; // 反弹振幅(像素)Math.sin(time * bounceFreq * Math.PI * 2) * bounceAmp;3. 使用函数实现可复用性
Section titled “3. 使用函数实现可复用性”// 定义一个可复用的缓动函数function easeInOut(t) { return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;}
// 使用函数var progress = time / 2; // 2秒动画easeInOut(progress) * 100;常见错误规避
Section titled “常见错误规避”- 忘记分号 - 始终用分号结束语句
- 大小写敏感 - JavaScript是大小写敏感的 (
Time≠time) - 数组索引 - 数组从索引0开始,而不是1
- 无限循环 - 在表达式中小心使用while循环
🔗 相关链接
Section titled “🔗 相关链接”掌握基础后,我们建议继续学习: