Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

HTML5 | Canvasで交差点を描く

概要

Canvasで交差点を描く

内容

CodeIQの結城先生の問題のクロッシング問題をやろうかな、
と思って気がついたら図を描画する方に手が動いていたという謎。
HTML5canvasで実装しました。

ソース

<html>
<head>
  <script type="text/javascript">
  function draw(list) {
    var canvas = document.getElementById('cv');
    var ctx = canvas.getContext('2d');

    draw_line(ctx, list, 30, 10, 30 + 50 * list.length, 10);
    draw_line(ctx, list, 30, 500, 30 + 50 * list.length, 500);

    for (i = 0; i < list.length; i++) {
      draw_line(ctx, list, 50 * (i + 1), 10, 50 * list[i], 500);
    }
  }

  function draw_line(ctx, list, start_x, start_y, end_x, end_y) {
    ctx.beginPath();
    ctx.moveTo(start_x, start_y);
    ctx.lineTo(end_x, end_y);
    ctx.stroke();
  }
  </script>
</head>
<body onload="draw(new Array(3, 4, 2, 1, 8, 6, 7, 5))" style="background-color:#eeeeee;">
  <canvas id="cv" style="border-style:groove;" width="1200" height="600"></canvas>
</body>
</html>

画像