不确定这是否可行,但我正在寻找一种在2个移动(动画)元素之间画线的方法。我知道你不能用CSS这样设置一个位置,但我知道你可以扭曲一条线,但这是用%完成的,所以你不能在这里设置一个位置。
我已经包括了一个工作小提琴。此外,动画是滞后的,如果可能的话,需要更自然。
// HTML
<div id="dotcontainer">
<div id="dot-1" class="dots">
<div class="dot"></div>
</div>
<div id="dot-2" class="dots">
<div class="dot"></div>
</div>
<div id="dot-3" class="dots">
<div class="dot"></div>
</div>
</div>
// JS
$(document).ready(function() {
animateDiv( $('#dot-1 .dot') );
animateDiv( $('#dot-2 .dot') );
animateDiv( $('#dot-3 .dot') );
});
function makeNewPosition($container) {
// Get viewport dimensions (remove the dimension of the div)
$container = ($container || $(window))
var h = $container.height() - 10;//10 is dot size
var w = $container.width() - 10;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh, nw];
}
function animateDiv($tar) {
var $target = $tar;
var newq = makeNewPosition($target.parent());
var oldq = $target.offset();
var speed = calcSpeed([oldq.top, oldq.left], newq);
//var speed = 1000;
$tar.animate({
top: newq[0],
left: newq[1]
}, speed, function() {
animateDiv($(this));
});
};
function calcSpeed(prev, next) {
var x = Math.abs(prev[1] - next[1]);
var y = Math.abs(prev[0] - next[0]);
var greatest = x > y ? x : y;
var speedModifier = 0.1;
var speed = Math.ceil(greatest / speedModifier);
return speed;
}
// CSS
#dotcontainer{
position: relative;
width: 500px;
height: 400px;
background: #eee;
}
.dots{
position: absolute;
background-color: #ccc;
height: 25px;
width: 25px;
}
.dot{
height: 20px;
width: 20px;
border-radius: 50%;
background-color: #333;
position: absolute;
top: 0;
left: 0;
}
#dot-1{
top: 60px;
left: 100px;
}
#dot-2{
top: 100px;
left: 290px;
}
#dot-3{
top: 230px;
left: 250px;
}