canvas實現的逐步成長的大樹效果

admin發表於2017-02-13
分享一段程式碼例項,它實現了逐步成長的大樹效果。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
#canvas {
  background: #ccc;
}
#tree {
  background: #eeffee;
}
</style>
<script>
window.onload = function() {
    var tree = document.getElementById('tree');
    var ctx = tree.getContext('2d');
    drawTree(ctx, tree.width / 2, tree.height - 50, 60, -Math.PI / 2, 11, 12);
    drawTree(ctx, tree.width / 2 - 60, tree.height, 20, -Math.PI / 2, 5, 3);
    drawTree(ctx, tree.width / 2 + 60, tree.height - 20, 20, -Math.PI / 2, 6, 3);
    drawTree(ctx, 70, 150, 20, -Math.PI / 2, 8, 3);
  }
  /**
   * [drawTree description]
   * @param  ctx         [畫布]
   * @param  startX      [樹的起始 x 座標]
   * @param  startY      [樹的起始 y 座標]
   * @param  length      [樹幹長度]
   * @param  angle       [樹幹方向,以座標系x軸正方向為0度]
   * @param  depth       [樹幹的節數]
   * @param  branchwidth [樹幹寬度]
   */
function drawTree(ctx, startX, startY, length, angle, depth, branchwidth) {
  var rand = Math.random,
    newLength, newAngle, newDepth, maxBranch = 3,
    endX, endY, maxAngle = Math.PI / 4,
    /* 樹枝數量 */
    subBranches;
  ctx.beginPath();
  ctx.moveTo(startX, startY);
  endX = startX + length * Math.cos(angle);
  endY = startY + length * Math.sin(angle);
  ctx.lineCap = 'round';
  ctx.lineWidth = branchwidth;
  ctx.lineTo(endX, endY);
  if (depth <= 2) {
    /*顏色用了隨機數,這樣使顏色看起來有深有淺,比較符合實際 */
    ctx.strokeStyle = 'rgb(0,' + parseInt(((rand() * 64) + 128)) + ',0)'; 
  } else {
    /*顏色用了隨機數,這樣使顏色看起來有深有淺,比較符合實際 */
    ctx.strokeStyle = 'rgb(' + parseInt(((rand() * 64) + 64)) + ',50,25)'; 
  }
  ctx.stroke();
 
  newDepth = depth - 1;
  if (!newDepth) {
    return;
  }
  subBranches = rand() * (maxBranch - 1) + 1;
  branchwidth *= 0.7;
  setTimeout(function() {
    for (var i = 0; i < subBranches; i++) {
      newAngle = angle + rand() * maxAngle * 2 - maxAngle;
      newLength = length * (0.7 + rand() * 0.3);
      drawTree(ctx, endX, endY, newLength, newAngle, newDepth, branchwidth);
    }
  }, 100);
}
</script>
</head>
<body>
<canvas id="tree" width="800" height="500">您的瀏覽器不支援canvas標籤</canvas>
</body>
</html>

相關文章