canvas繪製太陽系運動效果

antzone發表於2017-06-16

分享一段程式碼例項,它利用canvas繪製了太陽系星球旋轉效果。

根據與太陽不同的距離,星球的旋轉速度也是不同的,當然只是一個大致的模擬。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
*{
  margin: 0;
	padding:0;
}
html,body{
  width: 100%;
}
#canvas{
  width: 100%;
  height: 100%;
  background:black;
  display: block;
  /*去掉canvas作為行內元素預設垂直方式而產生的下邊空白間距*/
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
var canvas = document.getElementById("canvas");
var cxt = canvas.getContext("2d");
var centerX = 0,
  cneterY = 0;

var time = 0;

centerX = window.innerWidth / 2;
cneterY = window.innerHeight / 2;

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

window.onresize = function() {
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
  // 獲取瀏覽器視窗的中心座標
  centerX = window.innerWidth / 2;
  cneterY = window.innerHeight / 2;
  // console.log("W:"+centerX + "H:"+cneterY);
};

function draw() {

  cxt.clearRect(0, 0, 10000, 10000);

  cxt.strokeStyle = "#fff";

  //畫軌道,因其是相對太陽靜止的,故與行星區分開來畫
  function drawTrack() {

    for (var i = 1; i < 9; i++) {
      cxt.beginPath();
      cxt.arc(centerX, cneterY, 50 * i, 0, 360, false);
      cxt.closePath();
      cxt.stroke();
    }

  }

  drawTrack();

  function Planet(x, y, radius, cycle, inColor, outColor) {
    this.x = x;
    this.y = y;
    this.radius = radius;
    this.cycle = cycle;
    this.inColor = inColor;
    this.outColor = outColor;

    this.draw = function() {
      cxt.save();
      cxt.translate(centerX, cneterY);

      cxt.rotate(time * 360 / this.cycle * Math.PI / 200);


      cxt.beginPath();
      cxt.arc(this.x, this.y, this.radius, 0, 360, false);
      cxt.closePath();

      var sunColor = cxt.createRadialGradient(this.x, this.y, 0, this.x, this.y, 20);
      sunColor.addColorStop(0, this.inColor);
      sunColor.addColorStop(1, this.outColor);
      cxt.fillStyle = sunColor;
      cxt.fill();
      cxt.restore();
      time++;
    }
  }

  var sun = new Planet(0, 0, 20, 0, "#f00", "#f90");
  sun.draw();

  var Mercury = new Planet(-50, 0, 10, 288, "#A69697", "#5C3E40");
  Mercury.draw();

  var Venus = new Planet(-100, 0, 10, 505, "#C4BBAC", "#1F1315");
  Venus.draw();

  var Earth = new Planet(-150, 0, 10, 565, "#78B1E8", "#050C12");
  Earth.draw();

  var Mars = new Planet(-200, 0, 10, 687, "#CEC9B6", "#76422D");
  Mars.draw();

  var Jupiter = new Planet(-250, 0, 10, 4333, "#C0A48E", "#322222");
  Jupiter.draw();

  var Saturn = new Planet(-300, 0, 10, 10760, "#F7F9E3", "#5C4533");
  Saturn.draw();

  var Uranus = new Planet(-350, 0, 10, 30099, "#A7E1E5", "#19243A");
  Uranus.draw();

  var Neptune = new Planet(-400, 0, 10, 165 * 320, "#0661B2", "#1E3B73");
  Neptune.draw();

}

setInterval(draw, 10);
</script>
</body>
</html>

相關文章