starwards-pixijs について
Starwardsのブラウザー描画を開発する人向けの、PixiJS v8リファレンスと実践スキルです。APIの解説に加え、レイヤー、イベント、オブジェクトプーリングのStarwards固有パターンを扱います。
主な機能
- 01PixiJS v8 APIリファレンス
- 02コンテナーとシーングラフの構成
- 03アセット、テクスチャ、描画
- 04Tickerによる更新とインタラクション
- 05Starwardsのレイヤーとプーリング
活用シーン
- 01ブラウザー向け2D描画の実装
- 02PixiJS v7コードのv8移行
- 03Starwardsのレーダーや戦術ビュー開発
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ starwards/ starwards --skill starwards-pixijsインストール後、Claude Code で/starwards-pixijsを入力して読み込まれたか確認します。
詳細
Starwards 向け PixiJS v8 開発
概要
Starwards では、ブラウザーモジュールの 2D レンダリングに PixiJS v8(^8.14.0)を使用しています。このスキルでは、PixiJS v8 の API リファレンスと Starwards 固有のパターンの両方を扱います。
基本原則: レイヤー化されたコンテナーの合成により、Colyseus の状態変更と同期したティッカー駆動の更新を行います。
目次
PixiJS v8 リファレンス
Application
Application クラスは、PixiJS プロジェクトの拡張可能なエントリーポイントを提供します。
非同期初期化(v8 では必須)
import { Application } from 'pixi.js';
const app = new Application();
await app.init({
width: 800,
height: 600,
backgroundColor: 0x1099bb,
});
document.body.appendChild(app.canvas);
主なオプション
| オプション | 型 | デフォルト | 説明 |
|---|---|---|---|
width | number | 800 | 初期幅 |
height | number | 600 | 初期高さ |
backgroundColor | ColorSource | 'black' | 背景色 |
antialias | boolean | - | アンチエイリアスを有効にする |
resolution | number | 1 | ピクセル解像度 |
resizeTo | Window | HTMLElement | - | 自動リサイズの対象 |
preference | 'webgl' | 'webgpu' | 'webgl' | レンダラーの種類 |
コンテナーとシーングラフ
コンテナーの作成
import { Container } from 'pixi.js';
const container = new Container({
x: 100,
y: 100,
});
app.stage.addChild(container);
親子関係
- 子は親からトランスフォーム、アルファ、表示状態を継承します
- 描画順序:子は追加された順に描画されます(後から追加したものが前面になります)
- 並べ替えるには、
setChildIndex()を使うか、sortableChildrenとzIndexを併用します
座標系
// Local to global
const globalPos = obj.toGlobal(new Point(0, 0));
// Global to local
const localPos = container.toLocal(new Point(100, 100));
カリング
container.cullable = true; // Enable culling
container.cullableChildren = true; // Cull children recursively
container.cullArea = new Rectangle(0, 0, 400, 400); // Custom cull bounds
スプライト
基本的な使い方
import { Sprite, Assets } from 'pixi.js';
const texture = await Assets.load('bunny.png');
const sprite = new Sprite(texture);
sprite.anchor.set(0.5); // Center anchor
sprite.x = 100;
sprite.y = 100;
sprite.tint = 0xff0000; // Red tint
sprite.alpha = 0.8;
スプライトのプロパティ
| プロパティ | 説明 |
|---|---|
texture | 表示するテクスチャ |
anchor | 原点(0~1 の範囲) |
tint | 色合い |
blendMode | 合成時のブレンドモード |
width, height | サイズ(テクスチャを拡大縮小します) |
グラフィックス(v8 API)
重要: v8 では新しい流れるような API が使用されます。まず図形を作成し、その後に塗りつぶしや線を設定します。
v8 の流れるような API
import { Graphics } from 'pixi.js';
// Draw shape, then fill/stroke
const graphics = new Graphics()
.rect(50, 50, 100, 100)
.fill(0xff0000)
.stroke({ width: 2, color: 'white' });
// Circle with fill and stroke
const circle = new Graphics()
.circle(100, 100, 50)
.fill({ color: 0x00ff00, alpha: 0.5 })
.stroke({ width: 3, color: 0x000000 });
図形メソッド
| v7(旧) | v8(新) |
|---|---|
drawRect() | rect() |
drawCircle() | circle() |
drawEllipse() | ellipse() |
drawRoundedRect() | roundRect() |
drawPolygon() | poly() |
drawStar() | star() |
線
const lines = new Graphics()
.moveTo(0, 0)
.lineTo(100, 100)
.lineTo(200, 0)
.stroke({ width: 2, color: 0xff0000 });
穴(v8)
const rectWithHole = new Graphics()
.rect(0, 0, 100, 100)
.fill(0x00ff00)
.circle(50, 50, 20)
.cut(); // Creates hole
GraphicsContext(共有)
import { GraphicsContext, Graphics } from 'pixi.js';
const context = new GraphicsContext()
.rect(0, 0, 100, 100)
.fill(0xff0000);
const g1 = new Graphics(context);
const g2 = new Graphics(context); // Shares same data
テキスト
基本的なテキスト
import { Text, TextStyle } from 'pixi.js';
const text = new Text({
text: 'Hello World',
style: {
fontFamily: 'Arial',
fontSize: 24,
fill: 0xffffff,
align: 'center',
},
});
TextStyle のプロパティ
| プロパティ | 説明 |
|---|---|
fontFamily | フォント名 |
fontSize | ピクセル単位のサイズ |
fill | 塗りつぶし色 |
stroke | 線の設定 |
align | テキストの配置 |
wordWrap | 単語の折り返しを有効にする |
wordWrapWidth | 折り返し幅 |
BitmapText(パフォーマンス)
import { BitmapText } from 'pixi.js';
const bitmapText = new BitmapText({
text: 'Score: 1000',
style: { fontFamily: 'MyBitmapFont', fontSize: 32 },
});
テクスチャとアセット
アセットの読み込み
import { Assets, Sprite } from 'pixi.js';
// Single asset
const texture = await Assets.load('path/to/image.png');
const sprite = new Sprite(texture);
// Multiple assets
const textures = await Assets.load(['a.png', 'b.png']);
// With alias
await Assets.load({ alias: 'hero', src: 'images/hero.png' });
const heroTexture = Assets.get('hero');
アセットバンドル
Assets.addBundle('game', [
{ alias: 'player', src: 'player.png' },
{ alias: 'enemy', src: 'enemy.png' },
]);
const assets = await Assets.loadBundle('game');
マニフェスト
const manifest = {
bundles: [
{
name: 'load-screen',
assets: [{ alias: 'bg', src: 'background.png' }],
},
{
name: 'game',
assets: [{ alias: 'hero', src: 'hero.png' }],
},
],
};
await Assets.init({ manifest });
await Assets.loadBundle('load-screen');
SVG
// As texture
const svgTexture = await Assets.load('icon.svg');
const sprite = new Sprite(svgTexture);
// As Graphics (scalable)
const svgContext = await Assets.load({
src: 'icon.svg',
data: { parseAsGraphicsContext: true },
});
const graphics = new Graphics(svgContext);
テクスチャのクリーンアップ
// Unload from cache and GPU
await Assets.unload('texture.png');
// Unload from GPU only (keep in memory)
texture.source.unload();
// Destroy texture
texture.destroy();
ティッカー
基本的な使い方
import { Ticker, UPDATE_PRIORITY } from 'pixi.js';
// Using app ticker
app.ticker.add((ticker) => {
sprite.rotation += 0.1 * ticker.deltaTime;
});
// One-time callback
app.ticker.addOnce((ticker) => {
console.log('Called once');
});
// With priority (higher runs first)
app.ticker.add(updateFn, null, UPDATE_PRIORITY.HIGH);
優先度定数
UPDATE_PRIORITY.HIGH = 50UPDATE_PRIORITY.NORMAL = 0UPDATE_PRIORITY.LOW = -50
FPS の制御
app.ticker.maxFPS = 60; // Cap framerate
app.ticker.minFPS = 30; // Clamp deltaTime
ティッカーのプロパティ
| プロパティ | 説明 |
|---|---|
deltaTime | スケーリングされたフレーム差分 |
elapsedMS | 前のフレームからの実時間(ミリ秒) |
FPS | 現在の 1 秒あたりのフレーム数 |
イベント/インタラクション
イベントモード
sprite.eventMode = 'static'; // Interactive, non-moving
sprite.eventMode = 'dynamic'; // Interactive, moving (receives idle events)
sprite.eventMode = 'passive'; // Default, children can be interactive
sprite.eventMode = 'none'; // No interaction
ポインターイベント
sprite.eventMode = 'static';
sprite.on('pointerdown', (event) => {
console.log('Clicked at', event.global.x, event.global.y);
});
sprite.on('pointermove', (event) => { /* ... */ });
sprite.on('pointerup', (event) => { /* ... */ });
sprite.on('pointerover', (event) => { /* ... */ });
sprite.on('pointerout', (event) => { /* ... */ });
ヒット領域
import { Rectangle, Circle } from 'pixi.js';
sprite.hitArea = new Rectangle(0, 0, 100, 100);
// or
sprite.hitArea = new Circle(50, 50, 50);
カスタムカーソル
sprite.cursor = 'pointer';
sprite.cursor = 'grab';
sprite.cursor = 'url(cursor.png), auto';
子要素のインタラクションを無効化
container.interactiveChildren = false; // Skip children hit testing
パフォーマンスのヒント
スプライト
- テクスチャの切り替えを最小限に抑えるため、スプライトシートを使用します
- スプライトは、1バッチあたり最大16個のテクスチャでバッチ処理されます
- 描画順序はバッチ処理の効率に影響します
グラフィックス
- 作成後に変更しない場合、グラフィックスの処理が最速になります
- 小さなグラフィックス(100ポイント未満)はスプライトと同様にバッチ処理されます
- 複雑な形状には、テクスチャ付きスプライトを使用します
テキスト
- 毎フレームのテキスト更新は避けます(処理コストが高くなります)
- 頻繁に変化するテキストにはBitmapTextを使用します
- メモリ使用量を抑えるには、
resolutionを低くします
マスク
- 矩形マスク(scissor)が最速です
- グラフィックスマスク(stencil)は2番目に高速です
- スプライトマスク(filters)は処理コストが高くなります
フィルター
container.filters = nullで解放します- 寸法がわかっている場合は、
filterAreaを設定します - フィルターを使いすぎないようにします。フィルターごとに描画呼び出しが増えます
全般
- 大規模なシーンではカリングを有効にします:
cullable = true - 静的コンテンツには
RenderGroupsを使用します - インタラクションのないコンテナーでは、
interactiveChildren = falseを設定します
v8への移行に関する主なポイント
主な変更点
- 非同期初期化が必須
// OLD (v7)
const app = new Application({ width: 800 });
// NEW (v8)
const app = new Application();
await app.init({ width: 800 });
- Graphics APIの変更
// OLD (v7)
graphics.beginFill(0xff0000).drawRect(0, 0, 100, 100).endFill();
// NEW (v8)
graphics.rect(0, 0, 100, 100).fill(0xff0000);
- Tickerコールバック
// OLD (v7)
ticker.add((dt) => sprite.rotation += dt);
// NEW (v8)
ticker.add((ticker) => sprite.rotation += ticker.deltaTime);
- アプリケーションのCanvas
// OLD (v7)
app.view
// NEW (v8)
app.canvas
- リーフノードに子要素を設定できない
Sprite、Graphics、Meshなどには、子要素を設定できなくなりました- 代わりに
Containerを親として使用します
- getBoundsの戻り値がBoundsに変更
// OLD (v7)
const rect = container.getBounds();
// NEW (v8)
const rect = container.getBounds().rectangle;
Starwardsのパターン
CameraViewアプリケーション
Starwardsは、レーダー/戦術ビュー向けにApplicationを拡張します。
場所: modules/browser/src/radar/camera-view.ts
import { Application, ApplicationOptions, Container } from 'pixi.js';
export class CameraView extends Application {
constructor(public camera: Camera) {
super();
}
public async initialize(
pixiOptions: Partial<ApplicationOptions>,
container: WidgetContainer
) {
await super.init(pixiOptions);
// Limit FPS to prevent GPU heating
this.ticker.maxFPS = 30;
// Handle resize
container.on('resize', () => {
this.resizeView(container.width, container.height);
});
// Append canvas
container.getElement().append(this.canvas);
}
// Coordinate transformations
public worldToScreen = (w: XY) => this.camera.worldToScreen(this.renderer, w.x, w.y);
public screenToWorld = (s: XY) => this.camera.screenToWorld(this.renderer, s.x, s.y);
// Layer management
public addLayer(child: Container) {
this.stage.addChild(child);
}
}
主なパターン:
ticker.maxFPS = 30:GPUの過剰な使用を防ぎます- 座標変換:
worldToScreen()、screenToWorld() addLayer()によるレイヤー構成
レイヤーシステム
Starwardsでは各レイヤーがrenderRootコンテナーを持つレイヤーパターンを使用します。
GridLayerの例
場所: modules/browser/src/radar/grid-layer.ts
import { Container, Graphics } from 'pixi.js';
export class GridLayer {
private stage = new Container();
private gridLines = new Graphics();
constructor(private parent: CameraView) {
this.parent.events.on('screenChanged', () => this.drawSectorGrid());
this.stage.addChild(this.gridLines);
}
get renderRoot(): Container {
return this.stage;
}
private drawSectorGrid() {
// Clear and redraw
this.gridLines.clear();
// Draw lines using v8 API
this.gridLines
.moveTo(0, screen)
.lineTo(this.parent.renderer.width, screen)
.stroke({ width: 2, color: magnitude.color, alpha: 0.5 });
}
}
パターン:
- 各レイヤーが
stageコンテナーを所有します renderRootゲッターを通じて公開しますscreenChangedイベントで再描画します- 再描画の前に
graphics.clear()を使用します
Starwardsのグラフィックスパターン
v8のFluent APIの使用
// Drawing selection rectangle
const graphics = new Graphics();
graphics
.rect(min.x, min.y, width, height)
.fill({ color: selectionColor, alpha: 0.2 })
.stroke({ width: 1, color: selectionColor, alpha: 1 });
// Drawing grid lines
this.gridLines
.moveTo(0, screenY)
.lineTo(rendererWidth, screenY)
.stroke({ width: 2, color: lineColor, alpha: 0.5 });
クリアして再描画するパターン
private redraw() {
this.graphics.clear();
// ... draw new content
}
Starwardsのイベント処理
場所: modules/browser/src/radar/interactive-layer.ts
セットアップ
import { Container, FederatedPointerEvent, Rectangle } from 'pixi.js';
export class InteractiveLayer {
private stage = new Container();
constructor(private parent: CameraView) {
// Set cursor
this.stage.cursor = 'crosshair';
// Enable interaction
this.stage.interactive = true;
// Set hit area to full canvas
this.stage.hitArea = new Rectangle(
0, 0,
this.parent.renderer.width,
this.parent.renderer.height
);
// Register events
this.stage.on('pointerdown', this.onPointerDown);
this.stage.on('pointermove', this.onPointerMove);
this.stage.on('pointerup', this.onPointerUp);
// Update hit area on resize
this.parent.events.on('screenChanged', () => {
this.stage.hitArea = new Rectangle(
0, 0,
this.parent.renderer.width,
this.parent.renderer.height
);
});
}
private onPointerDown = (event: FederatedPointerEvent) => {
const screenPos = XY.clone(event.global);
const worldPos = this.parent.screenToWorld(screenPos);
// ... handle interaction
};
}
主なパターン:
stage.interactive = trueでイベントを有効にしますstage.hitArea = new Rectangle(...)でクリック可能な領域を定義します- リサイズ時にヒット領域を更新します
- 画面座標には
event.globalを使用します screenToWorld()でワールド座標に変換します
オブジェクトプーリング
場所: modules/browser/src/radar/texts-pool.ts
Starwardsでは、GCの負荷を軽減するためにイテレーターベースのプーリングを使用します。
export class TextsPool {
private texts: Text[] = [];
constructor(private container: Container) {}
*[Symbol.iterator]() {
let index = 0;
while (true) {
if (index >= this.texts.length) {
const text = new Text({ text: '', style: { ... } });
this.texts.push(text);
this.container.addChild(text);
}
const text = this.texts[index];
text.visible = true;
yield text;
index++;
}
}
return() {
// Hide unused texts
for (let i = this.usedCount; i < this.texts.length; i++) {
this.texts[i].visible = false;
}
}
}
// Usage
const textsIterator = this.textsPool[Symbol.iterator]();
for (const item of items) {
const text = textsIterator.next().value;
text.text = item.label;
text.x = item.x;
text.y = item.y;
}
textsIterator.return(); // Hide unused
Playwrightでのテスト
データ属性
E2Eテスト用に、Canvas要素にdata-idを追加します。
this.canvas.setAttribute('data-id', 'Tactical Radar');
Playwrightセレクター
// Select canvas by data-id
const canvas = page.locator('[data-id="Tactical Radar"]');
// Get attribute values
const zoom = await canvas.getAttribute('data-zoom');
RadarDriverパターン
class RadarDriver {
constructor(private canvas: Locator) {}
async getZoom() {
return Number(await this.canvas.getAttribute('data-zoom'));
}
async setZoom(target: number) {
await this.canvas.dispatchEvent('wheel', { deltaY: ... });
}
}
テスト時の考慮事項
- PixiJSコンポーネントのユニットテストはありません(視覚的な出力のため)
- Playwrightを使用したE2Eテストを行います
- 描画されたピクセルではなく、データ属性を使ってテストします
- Tweakpaneパネルには
data-idを使用します:page.locator('[data-id="Panel Name"]')
クイックリファレンス
| タスク | Starwardsのパターン |
|---|---|
| レイヤーの作成 | class MyLayer { stage = new Container(); get renderRoot() { return this.stage; } } |
| グラフィックスの描画 | graphics.rect(...).fill({...}).stroke({...}) |
| 再描画 | graphics.clear(); // then draw |
| インタラクティブ化 | stage.interactive = true; stage.hitArea = new Rectangle(...) |
| イベント | stage.on('pointerdown', handler) |
| 座標 | parent.worldToScreen(xy), parent.screenToWorld(xy) |
| FPS制限 | ticker.maxFPS = 30 |
| テストセレクター | page.locator('[data-id="..."]') |
よくある落とし穴
-
v7 の Graphics API を使用する
- 誤り:
beginFill()、drawRect()、endFill() - 正しい:
rect().fill().stroke()
- 誤り:
-
非同期の初期化を忘れる
- 誤り:
new Application({ width: 800 }) - 正しい:
await app.init({ width: 800 })
- 誤り:
-
Sprite に子を追加する
- v8 のリーフノードには子を追加できません
- 親には Container を使用します
-
Graphics をクリアしない
- 再描画する前に
graphics.clear()を呼び出します
- 再描画する前に
-
リサイズ時にヒットエリアが更新されない
- キャンバスのリサイズ時に
stage.hitAreaを更新します
- キャンバスのリサイズ時に
-
SVG がテクスチャとして読み込まれない
- SVG には
Texture.from()を使用します(GitHub issue #8694 の回避策)
- SVG には