# 描画

シーンは `draw` を通して描画します。論理単位で扱うイミディエイトモードの API です。バッチ処理された **WebGL2** レンダラーの上で動き、WebGL2 が使えない環境では自動で **Canvas 2D** にフォールバックします。どちらでもコードは同じです。

```ts playground
//+ import { Game } from "@debuffjp/core";
//+ import { Particles } from "@debuffjp/juice";
//+ const canvas = document.querySelector("#game")!;
//+ const game = new Game({ canvas, width: 320, height: 180, background: "#11140d" });
//+ // heroFrame: buff, drawn into a small canvas so this example needs no image file.
//+ const heroFrame = document.createElement("canvas");
//+ heroFrame.width = 24; heroFrame.height = 22;
//+ const g = heroFrame.getContext("2d")!;
//+ g.fillStyle = "#cffb2d"; g.beginPath(); g.roundRect(0, 0, 24, 22, 7); g.fill();
//+ g.fillStyle = "#11140d"; g.fillRect(14, 6, 3, 6); g.fillRect(19, 6, 3, 6);
//+ const groundY = 150;
//+ const hero = { x: 160, y: groundY, vx: 60, facingLeft: false, hurt: 0 };
//+ const particles = new Particles(() => game.random.next());
//+ let score = 0;
//+ let timer = 0;
//+ game.add({ id: "play", update(dt) {
//+ hero.x += hero.vx * dt;
//+ if (hero.x  280) hero.vx = -hero.vx;
//+ hero.facingLeft = hero.vx  1.5) {
//+ timer = 0; score++; hero.hurt = 1; game.camera.shake(0.3);
//+ particles.emit({ x: hero.x, y: hero.y - 12, count: 14, colors: ["#cffb2d", "#38bdf8", "#f472b6"], shape: "circle", size: [2, 5], gravity: 300 });
//+ }
//+ particles.update(dt);
//+ },
render(draw) {
  draw.withCamera(game.camera, () => {
    draw.sprite(heroFrame, hero.x, hero.y, { origin: [0.5, 1], flipX: hero.facingLeft, flash: hero.hurt });
    draw.rect(0, groundY, 320, 8, "#2f3a1f");
    particles.draw(draw);
  });
  draw.text(`score ${score}`, 4, 4, { font: "8px monospace", color: "#cffb2d" });
}
//+ }).go("play");
//+ game.start();
```

## API {#api}

| 呼び出し | 描くもの |
| --- | --- |
| `sprite(frame \| image, x, y, options?)` | 画像、またはスプライトシートのフレーム。オプション：`origin`、`scaleX`、`scaleY`、`rotation`、`flipX`、`flipY`、`alpha`、`tint`、`flash`、`smooth` |
| `rect(x, y, w, h, color)` | 塗りつぶした矩形 |
| `circle(x, y, radius, color)` | 塗りつぶした、アンチエイリアス付きの円 |
| `line(x1, y1, x2, y2, width, color)` | 線 |
| `text(string, x, y, options?)` | キャッシュされた、くっきりしたテキスト。オプション：`font`（既定は debuff sans。0.6 より前は `8px monospace`）、`color`、`align`、`baseline`、`alpha` |
| `push()` / `pop()`、`translate`、`scale`、`rotate` | 変換スタック |
| `withCamera(camera, fn)` | カメラの視点で `fn` を実行 |
| `clip(x, y, w, h, fn)` | 矩形の内側にだけ描く（UI パネル、リスト、ミニマップ）。入れ子にできます |
| `alpha`、`blend("normal" \| "add")` | 全体のアルファとブレンドモード |
| `raw` | `{ kind: "webgl2", gl }` または `{ kind: "2d", ctx }` の抜け道 |

色は 16 進文字列（`"#cffb2d"`、`"#cffb2d80"`）、任意の CSS カラー、または数値 `0xRRGGBBAA` で指定します。

## なぜ速いのか {#why-it-s-fast}

すべての呼び出しは GPU バッファの 1 インスタンスになります。1 バッチにつき最大 8 枚のテクスチャをバインドするので、スプライト、テキスト、パーティクルが混ざってもバッチが途切れません。ホットパスではメモリを確保しません。

debuff は [spryte](https://github.com/debuffjp/spryte) で描画しています。[レンダラーのベンチマーク](/ja/benchmarks)では、`draw.sprite` は **PixiJS の `Sprite` より約 2.6〜3.5 倍速く**、約 100,000 個のスプライトを 60 fps で描き続けます。パーティクルや弾幕、群れには `draw.sprites(frame, positions, count, options, each?)` を使えば、位置を並べた `Float32Array` を 1 回の呼び出しでまとめて描けます。コピーごとのスケール、回転、色も指定できます。こちらは **60 fps で約 800,000 スプライト** を描き、パーティクルごとにすべてのプロパティを変えた場合でも **PixiJS の `ParticleContainer` より 4.2 倍速い** 結果です。ノート PC の GPU 1 台での計測なので、目安として見てください（[計測方法と注意点](/ja/benchmarks)）。

## バックエンドを選ぶ {#choosing-a-backend}

```ts
new Game({ canvas, width, height, renderer: "auto" }); // デフォルト：WebGL2、なければ Canvas 2D
new Game({ canvas, width, height, renderer: "2d" }); // Canvas 2D を強制
```

`game.draw.kind` で、どちらが有効かわかります。Canvas 2D では、`tint` はアルファだけが反映されます。

## リニアな光でブレンドする {#blending-in-linear-light}

```ts
new Game({ canvas, width, height, blendSpace: "linear" });
```

0.34 から、`blendSpace` が spryte のレンダラーに渡るので、色をリニアな光で混ぜられます。グローは光のように足し合わされ、暗い背景の明るい文字も太さを保ちます。既定の `"srgb"` は CSS や Canvas 2D と同じ混ぜ方です。コストやデータ画像の印付けは [spryte のレンダラーオプション](/ja/spryte/getting-started#create-a-renderer)を見てください。0.34 より前は `Game` が `renderer` と `smooth` しか渡さなかったので、debuff のゲームからは有効にできませんでした。