gpt4 book ai didi

javascript - 使用 Curtains.js 在动画完成时运行函数

转载 作者:行者123 更新时间:2023-12-02 02:35:35 25 4
gpt4 key购买 nike

我希望在摆动效果结束时调用一个函数。

也就是说,在阻尼效果结束时(当摆动停止时),我想执行 GSAP 时间轴函数。我假设需要在 Curtains 的 onReady() 内部调用这种类型的“onComplete”函数,并且可能需要跟踪阻尼效果。我只熟悉GSAP的onComplete函数,但不知道如何在这里实现它。也许可以检查 deltas.applied 是否小于 0.001 ,然后调用该函数?

下面是代码片段(没有片段和顶点着色器)。完整的工作代码在这里: CodePen

class Img {
constructor() {
const curtain = new Curtains({
container: "canvas",
watchScroll: false,
});

const params = {
vertexShader,
fragmentShader,
uniforms: {
time: {
name: "uTime",
type: "1f",
value: 0,
},
prog: {
name: "uProg",
type: "1f",
value: 0,
}
}
}

const planeElements = document.getElementsByClassName("plane")[0];

this.plane = curtain.addPlane(planeElements, params);

if (this.plane) {
this.plane
.onReady(() => {
this.introAnim();
})
.onRender(() => {
this.plane.uniforms.time.value++;
deltas.applied += (deltas.max - deltas.applied) * 0.05;
deltas.max += (0 - deltas.max) * 0.07;
this.plane.uniforms.prog.value = deltas.applied
})
}

// error handling
curtain.onError(function() {
document.body.classList.add("no-curtains");
});
}

introAnim() {
deltas.max = 6;
//console.log("complete") <-- need an onComplete type function~!
}
}

window.onload = function() {
const img = new Img();
}

最佳答案

你可以使用一些代数:)

首先,您应该像这样简化您的 deltas.max 函数:

deltas.max += (0 - deltas.max) * 0.07;
// Simplifies to
deltas.max -= deltas.max * 0.07;
// Rewrite to
deltas.max = deltas.max - deltas.max * 0.07;
// Rewrite to
deltas.max = deltas.max * (1 - 0.07);
// Simplifies to
deltas.max *= 0.93; // Much nicer :)

这实际上非常重要,因为它使我们计算时间变量的最终值和动画持续时间的工作显着变得更加容易:

// Given deltas.max *= 0.93, need to calculate end time value
// endVal = startVal * reductionFactor^n
// Rewrite as
// n = ln(endVal / startVal) / ln(reductionFactor) // for more see https://www.purplemath.com/modules/solvexpo2.htm
// n = ln(0.001 / 8) / ln(0.93)
const n = 123.84;

// Assuming 60fps normally: n / 60
const dur = 2.064;

一旦我们有了这些值,我们所要做的就是创建一个线性补间,以该持续时间将时间动画到该值,并更新 onUpdate 中的 max 和 prog 值:

gsap.to(this.plane.uniforms.time, {
value: n,
duration: dur,
ease: "none",
onUpdate: () => {
this.deltas.applied += (this.deltas.max - this.deltas.applied) * 0.05;
this.deltas.max *= 0.93;
this.plane.uniforms.prog.value = this.deltas.applied;
},
onComplete: () => console.log("complete!")
});

然后你就“完成了!”当动画结束时!

为了确保您的 Curtains 动画即使在高刷新率的显示器上也能以正确的速率运行(即使是那些没有直接使用 GSAP 制作动画的显示器),关闭 Curtain 的 autoRendering 也是一个好主意并使用 GSAP 的股票代码代替:

const curtains = new Curtains({ container: "canvas", autoRender: false });
// Use a single rAF for both GSAP and Curtains
function renderScene() {
curtains.render();
}
gsap.ticker.add(renderScene);

总共你会得到 this demo .

关于javascript - 使用 Curtains.js 在动画完成时运行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64364972/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com