javascript canvasタグに円や半円を描画する

javascript canvasタグに円や半円を描画する

javascriptで、canvasタグを使って、円や半円を描画するサンプルコードを記述してます。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 102.0.5005.115

canvasタグ使い方

arcメソッドを使用すれば、円を作成することが可能です。

<canvas id="cvs"></canvas>

<script>

// 2D図形を扱う
let ctx = document.getElementById('cvs').getContext('2d');

// 枠色を指定
ctx.strokeStyle = "#eb2142";

// 円
ctx.beginPath();

// arc(中心x座標, 中心y座標, 半径, 円弧の開始角, 円弧の終了角, 描画の方向)
ctx.arc(50, 50, 20, 0, Math.PI * 2, false);
ctx.stroke();

</script>

実行結果

サンプルコード

以下は、
「作成」ボタンをクリックすると、canvasタグに円を作成する
サンプルコードとなります。

※cssには「bootstrap material」を使用してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons">
  <link rel="stylesheet"
    href="https://unpkg.com/bootstrap-material-design@4.1.1/dist/css/bootstrap-material-design.min.css" id="css">
</head>
<style>
  .main {
    margin: 0 auto;
    margin-top: 200px;
    display: flex;
    flex-direction: column;
    align-items: center;
    font-size: 30px;
  }
</style>
<script>

  function hoge() {

    // 2D図形を扱う
    let ctx = document.getElementById('cvs').getContext('2d');
    // 枠色を指定
    ctx.strokeStyle = "#eb2142";
    // 塗りつぶし色
    ctx.fillStyle = "#40b812";

    // 円 枠線
    ctx.beginPath();
    // arc(中心x座標, 中心y座標, 半径, 円弧の開始角, 円弧の終了角, 描画の方向)
    ctx.arc(80, 50, 20, 0, Math.PI * 2, false);
    ctx.stroke();

    // 円 塗りつぶし
    ctx.beginPath();
    ctx.arc(130, 50, 20, 0, Math.PI * 2, false);
    ctx.fill();

    // 半円
    ctx.beginPath();
    ctx.arc(180, 50, 20, 0, Math.PI, false);
    ctx.stroke();
  }

  window.onload = function () {

    // ボタンを取得
    let elmbtn = document.getElementById('btn');
    // クリックイベントを登録
    elmbtn.onclick = function () {
      hoge();
    };

  }

</script>

<body>
  <div class="main">

    <h2 class="badge badge-primary">canvas</h2>

    <canvas id="cvs"></canvas>

    <button id="btn" type="button" class="btn btn-raised btn-warning">
      作成
    </button>

  </div>
</body>

</html>

円が作成されていることが確認できます。