javascriptとcanvasで図形を描画する

プログラムだけで図形を描く方法。
ブラウザで表示できて、右クリックでダウンロード可能。

<canvas id="canvas" width="400" height="400"></canvas>

<script>
function draw() {
    var canvas = document.getElementById('canvas'),
    csWidth  = canvas.width,
    csHeight = canvas.height;

    if (canvas.getContext){
      var ctx = canvas.getContext('2d');
      // Filled triangle
      ctx.beginPath();
      ctx.moveTo(0,0);
      ctx.lineTo(csWidth,0);
      ctx.lineTo(0, csHeight);
      ctx.fill();
  
      // Stroked triangle
      ctx.beginPath();
      ctx.moveTo(csWidth,csHeight);
      ctx.lineTo(csWidth, 0);
      ctx.lineTo(0, csHeight);
      ctx.closePath();
      ctx.stroke();
    }
  }

  draw()
</script>
<canvas id="myCanvas" width="600" height="600"></canvas>

<script>
// 変数定義
var cs       = document.getElementById('myCanvas'),
    ctx      = cs.getContext('2d'),
    csWidth  = cs.width,
    csHeight = cs.height,
    center   = {
      x: csWidth / 2,
      y: csHeight / 2
    };

// 線の基本スタイル
ctx.strokeStyle = '#000';
ctx.lineWidth = 10;

// 横線を引く
var drawHorizontalLine = function() {
  ctx.beginPath();
  ctx.moveTo(0, center.y);
  ctx.lineTo(csWidth, center.y);
  ctx.closePath();
  ctx.stroke();
};

// 縦線を引く
var drawVerticalLine = function() {
  ctx.beginPath();
  ctx.moveTo(center.x, 0);
  ctx.lineTo(center.x, csHeight);
  ctx.closePath();
  ctx.stroke();
};

drawHorizontalLine();
drawVerticalLine();

</script>

コメント

タイトルとURLをコピーしました