Dart: Structured web apps [6] canvas

DartでもHTML5のcanvasが使えます。

Webアプリをウィザードで作成してから、HTMLを編集して、canvasを追加します。

    <div>
        <canvas id="canvas" width="300" height="300"></canvas>
    </div>

次に示すように、CanvasElementでHTML5のcanvas要素を取得して、CanvasRenderingContext2Dオブジェクトを取得します。ここでは、clearRectで長方形領域をクリア、fillRectで長方形領域を塗りつぶし、fillStyleで色指定、という処理をしています。

#import('dart:html');

class webapp {
  CanvasElement canvas;
  CanvasRenderingContext2D ctx;
  static final String COLOR = "gray";

  webapp() {
    canvas = document.query("#canvas");
    ctx = canvas.getContext("2d");
  }
  void drawFrame() {
    int w = canvas.width;
    int h = canvas.height;
    ctx.clearRect(0, 0, w, h);
    ctx.fillRect(10, 10, w-20, h-20);
    drawUnit(20, 20);
  }  
  void drawUnit(num x, num y) {
    ctx.fillStyle = COLOR;
    ctx.fillRect(x, y, 15, 15);
  }
  void run() {
    drawFrame();
  }
}

void main() {
  new webapp().run();
}

見ての通り、dart:htmlライブラリに含まれるCanvasのようなクラスはWebブラウザのIDLと自動的に結びつくようなので、HTML5のDOMについての知識が活かせます。なお、次のような特長があります。(参考:Sunflower Code Walkthrough | DartLang.org

  • arc(), fill()といったオブジェクトのメソッド名は変更されていない
  • オブジェクト属性について、JavaScriptでそうであるように、通常は同じ名前となる
  • イベントハンドラ(onXxxxメソッド)はイベント引数としてクロージャを指定するだけで簡単に用意できる

*「arc(), fill()といったオブジェクトのメソッド名は変更できない」を「arc(), fill()といったオブジェクトのメソッド名は変更されていない」と修正しました。

簡単ながら、DartでのCanvas利用方法を紹介しました。

同じタグの記事: Dart
同じタグの記事: dartlang
同じカテゴリの記事: Program