我有一个JavaScript函数,我写了一个红色的css球在屏幕上随机移动。问题是,因为它直接从一个位置到另一个位置,所以看起来并不那么平滑。当它改变位置时使它做曲线可能会使这更顺畅。基于提供的代码,这样做的好方法是什么?
$('#menu_button4').click(function(){
$('#ball').show();
cake = function(a,b,u) {return (1-u) * a + u * b;};
draw_pos = function(element, property1, property2, start, end, duration) {
var interval = 10;
var steps = duration/interval;
var step_u = 1.0/steps;
var u = 0.0;
var theInterval = setInterval(function(){
if (u >= 1.0){ clearInterval(theInterval) }
var s = parseInt(cake(start.s, end.s, u));
var d = parseInt(cake(start.d, end.d, u));
var x_pos = s+'%';
var y_pos = d+'%';
el.style.setProperty(property1, x_pos);
el.style.setProperty(property2, y_pos);
u += step_u;
}, interval);
};
el = document.getElementById('ball');
property1 = 'top';
property2 = 'left';
startdeg_1 = {s:'0', d:'0'};
enddeg_1 = {s:Math.floor((Math.random()*100)+1), d:Math.floor((Math.random()*100)+1)};
enddeg_2 = {s:Math.floor((Math.random()*100)+1), d:Math.floor((Math.random()*100)+1)};
enddeg_3 = {s:Math.floor((Math.random()*100)+1), d:Math.floor((Math.random()*100)+1)};
enddeg_4 = {s:Math.floor((Math.random()*100)+1), d:Math.floor((Math.random()*100)+1)};
enddeg_5 = {s:'40', d:'25'};
enddeg_6 = {s:'20', d:'20'};
draw_pos(el, property1, property2, startdeg_1, enddeg_1, 80);
setTimeout(function(){draw_pos(el, property1, property2, enddeg_1, enddeg_2, 80)}, 700);
setTimeout(function(){draw_pos(el, property1, property2, enddeg_2, enddeg_3, 80)}, 1400);
setTimeout(function(){draw_pos(el, property1, property2, enddeg_3, enddeg_4, 80)}, 2050);
setTimeout(function(){draw_pos(el, property1, property2, enddeg_4, enddeg_5, 80)}, 2650);
setTimeout(function(){draw_pos(el, property1, property2, enddeg_5, enddeg_6, 80)}, 3200);
});