requestAnimationFrame - 移动圈

时间:2016-03-10 17:36:21

标签: javascript html css animation requestanimationframe

我现在已经挣扎了一段时间,我似乎无法做到这一点。

我想要做的是,在一个容器内有一个 div 的圆圈,它也是一个 div 。我知道这可以用画布来实现,但我想用 divs

来做到这一点

这是我到目前为止所做的:

HTML

  <div class="box">
    <div class="circle" id="circle"></div>
  </div>

CSS

    .box {
        background-color:yellow;
        height:300px;
        width:500px;
        position: relative;
    }
    .circle {
        background-color:blue;
        height:50px;
        width:50px;
        border-radius:50%;
        position:absolute;
    }

JAVASCRIPT

    var floater = function(){

    requestAnimationFrame(floater);

    var circles = document.getElementById('ball');        
    circles.style.left = (((Math.sin(new Date() / 1000) + 1)) * 500) + "px";
    circles.style.bottom = (((Math.sin(new Date() / 1000) + 1)) * 300) + "px";

}

floater();

小提琴:https://jsfiddle.net/6nvg8pv0/4/

3 个答案:

答案 0 :(得分:0)

对于初学者,您必须将坐标限制在框内

mycircle.style.left = Math.min(450, (((Math.sin(new Date() / 1000) + 1)) * 500)) + "px";
mycircle.style.top = Math.min(250, (((Math.sin(new Date() / 1000) + 1)) * 300)) + "px";

答案 1 :(得分:0)

实际上你可以通过改变你将sin结果乘以

的值来限制运动在盒子里面
  mycircle.style.left = (((Math.sin(Date.now() / 1000)) + 1) * 225) + "px";
  mycircle.style.top = (((Math.sin(Date.now() / 1000)) + 1) * 125) + "px";

答案 2 :(得分:0)

为什么要在鼻窦上加1?你得到一个从0到2的值,所以圆的宽度和高度是两倍。用Math.abs取绝对值。删除+1。