更改动画的起点

时间:2016-06-19 10:57:50

标签: javascript css animation

我基于这个小提琴做了一个div的JavaScript动画:http://jsfiddle.net/Xw29r/15/我正在寻找一种方法来制作动画 开始 从一个确切的角度来看:
Top : 10vhLeft : 90vw,但如果不将动画放在窗口外,我似乎无法找到如何做到这一点

考虑使用像($(window).width()/100*9))这样的数学来获得大小。但似乎还没有成功。
我怎么能实现呢?

    $(document).ready(function(){
    animateDiv();

});

function makeNewPosition(){

    // Get viewport dimensions (remove the dimension of the div)
    var h = $(window).height() - 50;
    var w = $(window).width() - 50;

    var nh = Math.floor(Math.random() * h);
    var nw = Math.floor(Math.random() * w);

    return [nh,nw];    

}

function animateDiv(){
    var newq = makeNewPosition();
    var oldq = $('.a').offset();
    var speed = calcSpeed([oldq.top, oldq.left], newq);

    $('.a').animate({ top: newq[0], left: newq[1] }, speed, function(){
      animateDiv();        
    });

};

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;

}

1 个答案:

答案 0 :(得分:2)

使用CSS calc()如下所示:left: calc(90vw - 50px);使其保持在窗口内,只要窗口大于div本身。



$(document).ready(function(){
    animateDiv();
    
});

function makeNewPosition(){
    
    // Get viewport dimensions (remove the dimension of the div)
    var h = $(window).height() - 50;
    var w = $(window).width() - 50;
    
    var nh = Math.floor(Math.random() * h);
    var nw = Math.floor(Math.random() * w);
    
    return [nh,nw];    
    
}

function animateDiv(){
    var newq = makeNewPosition();
    var oldq = $('.a').offset();
    var speed = calcSpeed([oldq.top, oldq.left], newq);
    
    $('.a').animate({ top: newq[0], left: newq[1] }, speed, function(){
      animateDiv();        
    });
    
};

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;

}

div.a {
  top: 10vh;
  left: calc(90vw - 50px);
  width: 50px;
  height:50px;
  background-color:red;
  position:fixed;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='a'></div>
&#13;
&#13;
&#13;