LoginSignup
0
0

More than 3 years have passed since last update.

HTML canvasタグを使って描画

Posted at

前置き

HTMLで碁盤を作れないだろうか?と考えた。
CSSだけでは線が引けないことで悩んでいたら、HTMLのcanvasタグを使うとjavascriptで描画が出来るということで試してみた。

HTML側

HTMLの方は、canvasタグで描画される幅・高さを指定できる。
style属性を指定することで、背景色なども変更できる。

app/html/kifu.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>canvasで図形を描く</title>
<script type="text/javascript" src="../js/kifu.js">
</script>

</head>
<body onLoad="kifu()">
<h2>canvasで碁盤を描く</h2>
<canvas id="kifu"  width="400px" height="400px" style="background-color:#f78740;">
  碁盤を表示するには、canvasタグをサポートしたブラウザが必要です。
</canvas>
</body>
</html>

上のコードでは、幅(width)を400px、高さ(height)を400px、背景色を#f78740に指定している。bodyタグにあるkifu()はjavascript側の関数で、canvasタグの描画をする。

JavaScript側

描画のメインはこちら側に書く。

app/js/kifu.js
function kifu() {
//描画コンテキストの取得
var canvas = document.getElementById('kifu');

if (canvas.getContext) {

var context = canvas.getContext('2d');

context.strokeStyle = 'rgb(00,00,00)';
for (var x = 0; x < 8; x++) {
  for(var y = 0; y < 8; y++) {
    context.strokeRect(40+x*40, 40+y*40, 40, 40);
  }
}
var str = "_abcdefghi";
var game_record = [];
canvas.addEventListener("click", function(e) {
  var stone_x = Math.round(e.offsetX / 40);
  var stone_y = Math.round(e.offsetY / 40);
  var stone_x_code = str[stone_x];
  var stone_y_code = str[stone_y];
  var stone_code = stone_x_code + stone_y_code;
  if (!(game_record.includes(stone_code))) {
    game_record.push(stone_code)
    if (game_record.length % 2 == 0) {
      context.fillStyle = "rgb(255, 255, 255)";
      context.strokeStyle = "rgb(255, 255, 255)";
    } else {
      context.fillStyle = 'black';
      context.strokeStyle = 'black';
    }
    context.beginPath();
    context.arc(stone_x*40, stone_y*40, 19, 0, 2 * Math.PI, true);
    context.fill();
  }
  console.log(game_record);
}, false)
}
}

上のコードで、碁盤の格子と黒・白交互に盤面に石が置ける。
碁盤は、正方形を8×8個書くことで生成。
碁石は、奇数手、偶数手で塗りつぶされる色を変更して円で表現。
石取りの判定が入っていないので、囲碁ではないですね。
五目並べには使えるかな(笑)

後書き

ポートフォリオの題材に囲碁アプリを作りたかったんですが、棋譜再生方法、棋譜検討機能の実装で詰まってしまいました。
碁盤・碁石の描画だけはできるようになったので、アウトプットとして投稿します。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0