使图像以椭圆形方式移动

时间:2018-04-19 15:30:49

标签: javascript animation

我正试着拍一张溜冰场滑冰溜冰场的照片。这是我的代码,但我意识到这只会使溜冰者循环移动并且不适合溜冰场的图片。 那么如何进行癫痫运动?

x = 700  // center
y = 200   // center
r = 200   // radius
a = 0    // angle (from 0 to Math.PI * 2)

function rotate(a) {

    var px = x + r * Math.cos(a); // <-- that's the maths you need
    var py = y + r * Math.sin(a);

    document.querySelector('#point').style.left = px + "px";
    document.querySelector('#point').style.top = py + "px";  
}


setInterval(function() {
    a = (a + Math.PI / 360) % (Math.PI * 2);
    rotate(a);
}, 5);
</script>
<style>
div {
    position: fixed;
    width: 10px;
    height: 10px;
}

#center {
    left: 100px;
    top: 50px;
    background: black;
}

#imgLoper {
  left: 0px;
  width: 30px;
  height: 30px;
  top: 0px;
}
</style>
<body>
    <div id="center">
    <img src="bane.jpg" id="imgBane">
    </div>
    <div id="point">
    <img src="Lorentzen.png" id="imgLoper"></img>
    </div>
</body>

1 个答案:

答案 0 :(得分:0)

这可以让你获得椭圆运动:

var px = Math.cos(a)*w/2 
var py = Math.sin(a)*h/2

您可能需要进行一些调整以使其适合您的溜冰场

w = 700 // ellipse width
h = 200 // ellipse height
ellipseCenter = {
  "x": 340,
  "y": 90
}
a = 0 // angle (from 0 to Math.PI * 2)

function rotate(a) {

  var px = Math.cos(a) * w / 2 + ellipseCenter.x
  var py = Math.sin(a) * h / 2 + ellipseCenter.y
  document.querySelector('#point').style.left = px + "px";
  document.querySelector('#point').style.top = py + "px";
}


setInterval(function() {
  a = (a + Math.PI / 360) % (Math.PI * 2);
  rotate(a);
}, 5);
div {
  position: absolute;
}

#center {
  background: black;
  width: 700px;
  height: 200px;
}

#point {
  width: 20px;
  height: 20px;
  background-color: red;
  border-radius: 10px;
}
<div id="center">
  <div id="point">
  </div>
</div>