<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width, initial-scale=1.0"/><title>Document</title><script src="https://cdnjs.cloudflare.com/ajax/libs/tween.js/20.0.0/tween.umd.js"></script><style>.circle {width: 100px;height: 100px;
border-radius:50%;
background-color: orange;position: absolute;}
#box {
background-color: deeppink;width: 100px;height: 100px;}</style></head><body><div class="circle" style="top: 0px; left: 0px"></div><div id="box"></div><script>const position ={x:0};// position 对应初始位置 也就是left 是0pxconst div = document.querySelector(".circle");// 获取dom元素const tweenA =newTWEEN.Tween(position)// new TWEEN.Tween里面放置初始位置,也就是left 是0px.to({x:500},1000)// to函数第一个参数里面放置要到哪里 也就是left:500px的地方// to函数第二个参数是要花多少时间,也就是1000毫秒.onUpdate(function(){// onUpdate函数放置这段时间我们做什么,也就是div的left值不断变化,
div.style.left = position.x +"px";// position.x就是上面说的不断变化的left值,});
tweenA.start();// 启动这个动画
tweenA.yoyo(true)
tweenA.repeat(3)const box = document.getElementById("box");// Get the element we want to animate.const coords ={x:0,y:0};// Start at (0, 0)const tweenB =newTWEEN.Tween(coords,false)// Create a new tween that modifies 'coords'..to({x:300,y:200},1000)// Move to (300, 200) in 1 second.// .easing(TWEEN.Easing.Quadratic.InOut) // Use an easing function to make the animation smooth..onUpdate((object)=>{// console.log(object.x)// Called after tween.js updates 'coords'.// Move 'box' to the position described by 'coords' with a CSS translation.
box.style.setProperty("transform","translate("+ coords.x +"px, "+ coords.y +"px)");}).start();// Start the tween immediately.let data ={num:100};const tweenC =newTWEEN.Tween(data).to({num:230},1000).easing(TWEEN.Easing.Quadratic.InOut).onUpdate((a)=>{
num = Math.floor(data.num);
console.log(num);
box.innerText = num
}).start()functionanimate(){requestAnimationFrame(animate);// requestAnimationFrame可以看成setTimeout(animate, 17)
tweenA.update();// 每隔一段时间,update方法会调用上面的onUpdate函数,这样让left变化,小球位置也变化
tweenB.update();
tweenC.update();// tweenA.chain(tweenB)// tweenB.chain(tweenA)}animate();</script></body></html>