liguofeng29’s blog

個人勉強用ブログだっす。

HTML5のcanvas要素 - 四角を描く

四角を描く二つのメソッド

  1. fillRect(float x, float y, float width, float height)
  2. strokeRect(float x, float y, float width, float height)
<!DOCTYPE html>
<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=SJIS" />
   <title> 図形を描く </title>
</head>
<body>
<h2> 図形を描くサンプル </h2>
<canvas id="canvas" width="400" height="300"
    style="border:1px solid black"></canvas>
<script type="text/javascript">
   // canvas要素取得
   var canvas = document.getElementById("canvas");
   // CanvasRenderingContext2D取得
   var ctx = canvas.getContext("2d");

   // 赤
   ctx.fillStyle = "#f00";
   // 四角を描く
   ctx.fillRect(30, 20, 120, 60);
   
   // 黄
   ctx.fillStyle = "#ff0";
   // 四角を描く
   ctx.fillRect(80, 60, 120, 60);

   // 青
   ctx.strokeStyle = "#00f";
   // 幅
   ctx.lineWidth = 10;
   // 四角を描く
   ctx.strokeRect(30, 130, 120, 60);
   
   // 浅青
   ctx.strokeStyle = "#0ff";
   // 線スタイル
   ctx.lineJoin = "round";
   // 四角を描く
   ctx.strokeRect(80, 160, 120, 60);
   
   // ピンク
   ctx.strokeStyle = "#f0f";
   // 線スタイル
   ctx.lineJoin = "bevel";
   // 四角を描く
   ctx.strokeRect(130, 190, 120, 60);
</script>
</body>
</html>

f:id:liguofeng29:20160123181102p:plain