LoginSignup
0
0

More than 3 years have passed since last update.

konva.js で地図を描く (1)

Posted at

konva.jsとは

  • konva.js
    • デスクトップやモバイルアプリケーション向けの2Dキャンバスライブラリ
    • 図形や画像を描画したり、アニメーションしたり、イベントリスナーをつけたりなどが簡単にできる

今回はこのkonva.jsを使って簡易的な地図を描いた内容をまとめます

html側

samle.html
<html>
  <head>
    <meta charset="utf-8" />
  </head>
  <body>
    <div id="canvas-container"></div>
  </body>
</html>

html側はdivを用意するだけ

ライブラリ読み込み

スクリプトタグに以下埋め込み
<script src="https://unpkg.com/konva@7.0.3/konva.min.js"></script>

or

npm install konva

or

公式サイトからダウンロード

js側の実装

konva.jsの構造

公式サイトより引用

              Stage  <--- (1)divのidを取得してstageを用意
                |
         +------+------+
         |             |
       Layer         Layer  <--- (2)layerを用意
         |             |
   +-----+-----+     Shape  <--- (3)要素を用意。複数ある場合はグループ化できる
   |           |
 Group       Group
   |           |
   +       +---+---+
   |       |       |
Shape   Group    Shape
           |
           +
           |
         Shape
sample.js

// (1) divのidを取得してstageを用意
const stage = new Konva.Stage({
  container: 'canvas-container', //親要素のdivタグのidを指定
  width: 200, //キャンバスの横幅
  height: 200 //キャンバスの高さ
});

// (2)layerを用意
const layer = new Konva.Layer();

// (3)要素を用意。まずはマップの枠(四角)を用意
const box = new Konva.Rect({
  x: 0, //配置場所
  y: 0, //配置場所
  width: 200, //横幅
  height: 200, //高さ
  fill: "#ffffff", //塗り潰しの色
  stroke: "#000", //枠線の色
  strokeWidth: 1, //枠線の太さ
  opacity: 1, //透過率
  cornerRadius: [3, 3, 3, 3] //四角の角を丸める
});

layer.add(box); //作った四角をlayerにadd
stage.add(layer); //layerをstageにadd (階層の上に順番に追加していく)

layer.draw(); //これで描画


結果

まずこれで四角がcanvasに描かれる
(内部的にはこんな感じでdivの中にcanvasが生成されている)

result.html
<div id="canvas-container">
  <div class="konvajs-content" role="presentation" style="position: relative; user-select: none; width: 200px; height: 200px;">
  <canvas width="400" height="400" style="padding: 0px; margin: 0px; border: 0px; background: transparent; position: absolute; top: 0px; left: 0px; width: 200px; height: 200px; display: block;">
  </canvas>
  </div>
</div>
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