【发布时间】:2018-05-22 19:11:33
【问题描述】:
我正在尝试为我用 Vue.js 制作的计数器设置动画。
该值由Tween.js 进行动画处理,然后使用Numeral js 进行格式化,但我遇到了问题。
我想增加一个随机数量,当我增加时,将数字从当前显示的数字变为新的总数。
我有 num 保存计数器的最终值,displayNum 保存动画值。
问题是我当前的代码(如果你敲击增量按钮)有时会从 0 开始动画数字,而不是当前的总数。尤其是当你达到 1000 多个时。
我怎样才能阻止这种行为?
目前,每当您单击增量时,它都会采用当前显示的数字并开始对目标数字进行新的补间。
function animate(time) {
requestAnimationFrame(animate);
TWEEN.update(time);
}
requestAnimationFrame(animate);
var v = new Vue({
'el' : '#app',
'data' : {
num : 0,
displayNum : 0,
tween : false
},
methods:{
increment(){
var vm = this;
// select a random number and add it to our target
vm.num += Math.round(Math.random() * 300);
// create an object that we can use tween.js to animate
var anim = { num: vm.displayNum };
// if we are already animating, stop the animation
if( vm.tween ){
vm.tween.stop();
}
// create a new animation from the current number
vm.tween = new TWEEN.Tween(anim)
// to our new target
.to({ num : vm.num }, 3000)
.easing(TWEEN.Easing.Quadratic.Out)
.onUpdate(function() {
// Failed attempt to debug
if( anim.num < vm.displayNum ){
console.log("Something isn't right");
}
// on update, replace the display number with a rounded, formatted
// version of the animating number
vm.displayNum = numeral(Math.round(anim.num)).format('0,0');
})
// if the tween ever stops, set the vm's current tween to
// false
.onStop(function(){
vm.tween = false;
})
.start();
}
}
})
html, body{
height:100%;
}
body{
display:flex;
align-items:center;
justify-content:center;
}
.window{
width:200px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.6.1/css/bulma.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/numeral.js/2.0.6/numeral.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tween.js/r14/Tween.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js"></script>
<div id="app">
<div class="window has-text-centered">
<div class="is-size-1">
<span v-html="displayNum"></span>
</div>
<div>
<button class="button" @click="increment">Increment</button>
</div>
<div class="is-size-7">
<span v-html="num"></span>
</div>
</div>
</div>
【问题讨论】:
标签: vue.js tweenjs numeral.js