如何从后到前制作物体轨道?

时间:2015-07-24 05:53:45

标签: javascript jquery css3 animation canvas

是否有可能围绕另一个物体围绕另一个物体进行轨道运行?然后到前面?

我已经看到它完成旋转动画,在周边做了整整360,但是想知道是否有可能以某个角度进行。

我找不到任何可以做到这一点的资源,所以我已经包含了我想要完成的图像示例。红线是绕蓝色圆圈运行的物体。

非常感谢 - 我真的很感激帮助!

orbit

1 个答案:

答案 0 :(得分:4)

我想我会用<canvas>

写一个解决方案

var x, y, scale, state,  // Variables we'll use later.
    canvas = document.getElementById("canvas"), // Get the canvas,
    ctx = canvas.getContext("2d"),             // And it's context.
    counter = 0,          // Counter to increment for the sin / cos functions.
    width = 350,          // Canvas width.
    height = 200,         // Canvas height.
    centerX = width / 2,  // X-axis center position.
    centerY = height / 2, // Y-axis center position.
    orbit = {             // Settings for the orbiting planet:
      width: 150,         //   Orbit width,
      height: 50,         //   Orbit height,
      size: 10            //   Orbiting planet's size.
    };

canvas.width = width;   // Set the width and height of the canvas.
canvas.height = height;

function update(){
  state = counter / 75; // Decrease the speed of the planet for a nice smooth animation.
  x = centerX + Math.sin(state) * orbit.width;  // Orbiting planet x position.
  y = centerY + Math.cos(state) * orbit.height; // Orbiting planet y position.
  scale = (Math.cos(state) + 2) * orbit.size;  // Orbiting planet size.

  ctx.clearRect(0, 0, width, height); // Clear the canvas

  // If the orbiting planet is before the center one, draw the center one first.
  (y > centerY) && drawPlanet();
  drawPlanet("#f00", x, y, scale); // Draw the orbiting planet.
  (y <= centerY) && drawPlanet();

  counter++;
}

// Draw a planet. Without parameters, this will draw a black planet at the center.
function drawPlanet(color, x, y, size){
  ctx.fillStyle = color || "#000";
  ctx.beginPath();
  ctx.arc(x || centerX,
          y || centerY,
          size || 50,
          0,
          Math.PI * 2);
  ctx.fill();
}

// Execute `update` every 10 ms.
setInterval(update, 10);
<canvas id="canvas"></canvas>

如果你想改变轨道行星的旋转方向,只需替换:

x = centerX + Math.sin(state) * orbit.width;
y = centerY + Math.cos(state) * orbit.height;

使用:

x = centerX + Math.cos(state) * orbit.width;
y = centerY + Math.sin(state) * orbit.height;
//                  ^ Those got switched.

可以通过修改75

来更改轨道的速度
state = counter / 75;