canvas translate()、scale()和rotate()方法程式碼例項

admin發表於2018-06-05
本章節分享一段程式碼例項,它演示了標題中三個方法的用法。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<script>
function draw() {
  var canvas = document.getElementById("canvas");
  if (canvas == null) {
    return false;
  }
  var context = canvas.getContext("2d");
  context.fillStyle = "#eeeefe";
  context.fillRect(0, 0, 400, 300);
  //圖形繪製
  context.translate(200, 50);
  //左移動 200,下移動50
  context.fillStyle = "rgba(255,0,0,0.5)";
  for (var i = 0; i < 100; i++) {
    context.translate(25, 25);
    context.scale(0.95, 0.95);//縮小
    context.rotate(Math.PI / 10);
    context.fillRect(0, 0, 100, 50);
  }
}
window.onload = function () {
  draw()
}
</script>
</head>
<body>
<canvas id="canvas" width="400" height="300"></canvas>
</body>
</html>

相關文章