К основному содержанию
скилл CX Codex

pixijs-rendering — скилл для Claude Code: что делает и как установить

Скилл для сборки слоя рендера на PixiJS v8: асинхронный Application, загрузка текстур, сцена на Container, тикер и события указателя.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add gamedev-skills/awesome-gamedev-agent-skills --skill pixijs-rendering -a claude-code
Открыть на GitHub

Что делает pixijs-rendering

Скилл описывает сборку слоя рендера на PixiJS v8. Сначала пустой new Application(), потом await app.init({...}) — вся конфигурация уходит туда, а в DOM вставляется app.canvas. Текстуры грузятся через Assets.load, для набора ассетов есть манифест с бандлами. Класса Loader в восьмой версии больше нет.

Дальше сцена. Всё висит на app.stage, вложенность задаётся через Container, порядок отрисовки равен порядку добавления детей. Анимация идёт через app.ticker.add, скорость считается по ticker.deltaMS или deltaTime, потому что иначе движение привязано к частоте кадров. События включаются вручную: eventMode = 'static', затем pointerdown. Перетаскивание требует globalpointermove — обычный pointermove перестаёт приходить, как только курсор ушёл за край объекта.

Отдельный раздел — типовые поломки. Пустой canvas обычно значит, что забыли await app.init(), а app.view пишет предупреждение об устаревании. Крупные статичные поддеревья выносятся в render group через isRenderGroup: true. Примеры сверены с 8.22, поэтому код на v7 (синхронный конструктор, Loader, beginFill) скилл не разбирает: сперва нужна миграция. Это повод проверить package.json до установки.

Какие задачи решает

  • поднять асинхронный Application и не получить пустой canvas
  • загрузить текстуры через Assets, минуя удалённый Loader
  • сделать движение независимым от частоты кадров
  • починить перетаскивание, которое обрывается за краем спрайта
  • сгруппировать статичный фон в render group

Примеры запросов агенту

  • Собери сцену на PixiJS v8: асинхронный Application, фон и спрайт по центру экрана
  • Canvas пустой, а app.screen падает — что не так с моим new Application({...})?
  • Добавь спрайту перетаскивание, чтобы он не отставал от курсора за своими границами

Как установить pixijs-rendering

1Через Skills CLI (Vercel)

npx skills add gamedev-skills/awesome-gamedev-agent-skills --skill pixijs-rendering -a claude-code

2Вручную: положить файлы

~/.claude/skills/pixijs-rendering/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/pixijs-rendering/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о pixijs-rendering

Как установить pixijs-rendering в Claude Code?

Выполни npx skills add gamedev-skills/awesome-gamedev-agent-skills --skill pixijs-rendering -a claude-code. После этого файл скилла лежит по пути ~/.claude/skills/pixijs-rendering/SKILL.md.

Что делает pixijs-rendering?

Помогает собрать и отладить слой рендера на PixiJS v8: инициализация Application, загрузка ассетов, дерево сцены, цикл тикера, события указателя и render groups. Внутри также разобраны частые ошибки вроде пустого canvas.

Работает ли скилл с PixiJS v7?

Нет, он рассчитан только на v8. Код на v7 (синхронный конструктор Application, Loader, beginFill) сначала нужно перевести на восьмую версию.

Исходный текст

SKILL.md · Apache-2.0
---
name: pixijs-rendering
description: >
  Build a PixiJS v8 render layer: create the async Application, load textures with
  Assets, compose the scene graph with Container and Sprite, drive the ticker loop,
  wire pointer events, and group draws with render groups. Use when building or
  debugging PixiJS v8 — when the user mentions PixiJS, Pixi, Application, app.stage,
  Container, Sprite, Assets.load, app.ticker, or eventMode. Pins the v8 async
  init() API (examples checked against 8.22).
---

# PixiJS 8.22 Rendering

Set up and structure a PixiJS **8.22** application: the async `Application`, asset
loading via `Assets`, the `Container`/`Sprite` scene graph, the ticker loop,
pointer events, and render groups. Pins the 8.22 API (async `init`, unified
`Assets`, `eventMode`).

## When to use

- Use when starting a PixiJS v8 project, fixing a blank canvas, structuring the
  display list, loading textures, animating via the ticker, or handling pointer
  input.
- Use when `package.json` depends on `pixi.js` (v8) and code does
  `import { Application } from 'pixi.js'`.

**When *not* to use:** Phaser's scene/loader model → `phaser-core`. 3D scenes →
`threejs-scene-setup`. PixiJS v7-and-earlier code (synchronous `new
Application({...})`, `Loader`, `beginFill`/`endFill`) needs the v8 migration first;
this skill targets v8 only. (`interactive = true` still works in v8 as an alias for
`eventMode = 'static'`, but prefer the explicit `eventMode`.)

## Core workflow

1. **Create and `await` the Application.** In v8, `new Application()` is empty;
   configuration happens in `await app.init({...})`. Append `app.canvas` (not
   `app.view`) to the DOM. Wrap top-level `await` in an async function for bundlers.
2. **Load assets with `Assets`.** `await Assets.load(url)` returns a `Texture`. For
   many assets, register a manifest/bundle and load by name. There is no v7 `Loader`.
3. **Build the scene graph.** Everything descends from `app.stage` (a `Container`).
   Group related objects in `Container`s; child transforms are relative to the
   parent. Draw order = insertion order (later = on top).
4. **Animate with the ticker.** `app.ticker.add((ticker) => {...})`. Scale motion by
   `ticker.deltaTime` (frames, ~1 at 60fps) or `ticker.deltaMS` (milliseconds) so
   speed is frame-rate independent.
5. **Enable events per object** by setting `eventMode = 'static'` (or `'dynamic'`),
   then `obj.on('pointerdown', ...)`. Federated pointer events cover mouse/touch/pen.
6. **Promote big static subtrees to render groups** (`isRenderGroup: true`) so the
   GPU caches their transforms. Profile before and after; confirm pixels on screen.

## Patterns

### 1. Async Application boot (the v8 entry point)

```js
import { Application, Assets, Sprite } from 'pixi.js';

(async () => {
  // v8: construct empty, then await init(). Config does NOT go in the constructor.
  const app = new Application();
  await app.init({
    background: '#1099bb',
    resizeTo: window,        // track the window size
    antialias: true,
    // preference: 'webgpu',  // hint only; default order tries 'webgl' first.
    //                        // Pixi falls back if the backend is unavailable —
    //                        // branch on app.renderer.name, don't assume it took.
  });

  document.body.appendChild(app.canvas); // v8 uses app.canvas, not app.view

  const texture = await Assets.load('https://pixijs.com/assets/bunny.png');
  const bunny = new Sprite(texture);
  bunny.anchor.set(0.5);
  bunny.position.set(app.screen.width / 2, app.screen.height / 2);
  app.stage.addChild(bunny);
})();
```

### 2. Containers for a relative-transform scene graph

```js
import { Container, Sprite } from 'pixi.js';

const world = new Container();
app.stage.addChild(world);

// Children are positioned relative to `world`; move/scale/rotate the whole group
// by transforming the parent.
for (let i = 0; i < 10; i++) {
  const coin = new Sprite(coinTexture);
  coin.x = i * 40;
  world.addChild(coin);
}
world.position.set(100, 100);
world.scale.set(2);            // every coin scales with the container
```

### 3. The ticker loop (frame-rate independent)

```js
let elapsed = 0;
app.ticker.add((ticker) => {
  // deltaTime ≈ 1 at 60fps; deltaMS is milliseconds since last frame.
  elapsed += ticker.deltaMS;
  bunny.rotation += 0.05 * ticker.deltaTime;          // smooth at any frame rate
  bunny.y = app.screen.height / 2 + Math.sin(elapsed / 500) * 50;
});
```

### 4. Pointer events (federated)

```js
bunny.eventMode = 'static';   // 'static' = interactive, doesn't move on its own
bunny.cursor = 'pointer';     // hover cursor; `buttonMode` was removed in v8
bunny.on('pointerdown', (event) => {
  bunny.tint = 0xff0000;
  // event.global is the pointer position in stage space.
});
bunny.on('pointerover', () => bunny.scale.set(1.1));
bunny.on('pointerout',  () => bunny.scale.set(1.0));
```

Dragging needs `globalpointermove`, not `pointermove`. In v8 `pointermove` fires
**only while the pointer is over the object**, so a drag that follows the cursor
past the object's edge stops updating. `globalpointermove` fires on every move:

```js
let dragging = false;
bunny.on('pointerdown', () => { dragging = true; });
bunny.on('pointerup', () => { dragging = false; });
bunny.on('pointerupoutside', () => { dragging = false; }); // release off the object
bunny.on('globalpointermove', (event) => {
  if (dragging) bunny.position.copyFrom(event.global);
});
```

### 5. Loading many assets by name (bundles)

```js
import { Assets } from 'pixi.js';

await Assets.init({
  manifest: {
    bundles: [{
      name: 'level-1',
      assets: [
        { alias: 'hero',  src: 'assets/hero.png' },
        { alias: 'tiles', src: 'assets/tiles.png' },
      ],
    }],
  },
});

const bundle = await Assets.loadBundle('level-1'); // { hero: Texture, tiles: Texture }
const hero = new Sprite(bundle.hero);
```

### 6. Render groups for large static layers

```js
// A big, rarely-changing background subtree: let the GPU cache its transforms.
const background = new Container({ isRenderGroup: true });
app.stage.addChild(background);
// Add hundreds of static tiles to `background`. Moving `background` itself stays
// cheap; constantly re-adding/removing children negates the benefit.
```

## Pitfalls

- **Blank canvas, or `TypeError` reading `canvas`/`screen` of undefined** → you didn't
  `await app.init()`, or you configured the constructor. In v8 the constructor is
  empty; all options go to `init()`. `app.stage` exists right away, but
  `app.renderer` is `undefined` until the `init()` promise resolves, so `app.canvas`
  and `app.screen` throw before then.
- **`app.view` logs a deprecation warning** → v8 renamed it to `app.canvas`; the old
  getter still returns the canvas for now.
- **Porting v7 code** → `Loader`/`loader.add` → `Assets.load` (the `Loader` class is
  gone); synchronous `new Application({...})` → empty constructor + async `init()`
  (options in the constructor are ignored with a deprecation warning, not an error);
  `beginFill()`/`endFill()` → shape-first `.rect(...).fill(...)`. `interactive = true`
  and `app.view` still work as deprecated aliases.
- **Ticker callback arg is the Ticker, not a delta number** → `app.ticker.add((dt) =>
  { obj.rotation += dt; })` compiles, but `dt` is the whole `Ticker` object, so the
  math yields `NaN` and nothing animates. Read `ticker.deltaTime` off the argument.
- **Top-level await build error (Vite ≤6.0.6)** → wrap boot in `(async () => { ... })()`.
- **Speed varies with frame rate** → multiply movement by `ticker.deltaTime` (~1 at
  60fps) or scale by `ticker.deltaMS`; never assume 60fps. `deltaTime` is a
  dimensionless multiplier, not milliseconds.
- **Clicks do nothing** → the object's `eventMode` is still `'passive'` (the v8
  default: self not interactive, children still are); set it to `'static'` (or
  `'dynamic'` for objects that move under a stationary cursor).
- **Drag stops at the object's edge** → `pointermove` fires only while the pointer is
  over the object in v8; use `globalpointermove` for drag/global tracking.
- **Right-click opens the browser menu over the game** → PixiJS does not block it.
  From 8.22, listen for `contextmenu` on the object and call
  `event.preventDefault()`; cancelling `rightdown`/`rightclick` does not stop the menu.
  On older 8.x, add a native `contextmenu` listener to `app.canvas` instead.
- **`addChild` on a `Sprite`/`Graphics`/`Text` logs a deprecation warning** → in v8
  only `Container`s should hold children; put the sprite and its children side by side
  in a `Container`.
- **`Texture.from(url)` returns a blank/undefined texture** → in v8 it only reads the
  Assets cache; `await Assets.load(url)` first, then use the returned `Texture`.
- **WebGPU features error out** → `preference` is a hint. If the backend is
  unavailable Pixi falls back (WebGL, then Canvas); branch on `app.renderer.name`
  before using backend-specific code.
- **Textures look blurry on pixel art** → set
  `texture.source.scaleMode = 'nearest'` (or pass it when loading).
- **Memory grows** → `removeChild` does not free GPU memory; call
  `sprite.destroy()` and `Assets.unload(url)` for assets you're done with.
- **Flicker/corruption after tearing down and re-creating an app in the same tab** →
  destroy with `app.destroy({ releaseGlobalResources: true })`; otherwise pooled
  batches/textures from the old app leak into the new one.

## References

- For the texture/asset pipeline (sprite sheets/atlases, `Assets.add`, background
  loading, unloading) and Graphics/Text/`TilingSprite`/`ParticleContainer` plus
  filters, read `references/assets-and-display.md`.

## Related skills

- `phaser-core` — a batteries-included 2D framework (scenes, physics, input).
- `threejs-scene-setup` — 3D in the browser with three.js.
- `prototype-fast` — greybox a playable slice quickly (often cites PixiJS).

© gamedev-skills · Apache-2.0 · gamedev-skills/awesome-gamedev-agent-skills

Похожие скиллы

Всё по теме «Геймдев и 3D: Unity, Unreal, Godot, Blender» →
pixijs-custom-rendering pixijs Помогает писать кастомные шейдеры, юниформы, фильтры и батчеры в PixiJS v8 — на GLSL и WGSL, под WebGL и WebGPU. CX Codex +1 5 700установок pixijs-core-concepts pixijs Объясняет, как PixiJS v8 рисует кадры: выбор бэкенда, цикл рендера, работа с RenderTexture и потеря контекста. CX Codex +1 6 000установок pixijs-2d freshtechbro Скилл обучает агента создавать 2D-графику на PixiJS с WebGL и WebGPU: анимировать спрайты, выводить частицы и рисовать векторные фигуры на холсте. CX Codex +1 2 500установок v4-new-features phaserjs Скилл для изучения обновлений Phaser 4: Filters вместо FX, RenderNodes, новые игровые объекты (CaptureFrame, Gradient, Noise, SpriteGPULayer) и режимы тинта. Помогает разобраться в переписанном движке рендеринга. CX Codex +1 960установок blender-rendering RobLe3 Настраивает движки Cycles и EEVEE в Blender, выставляет сэмплы, денойзинг и профиль AgX. Помогает генерировать финальные кадры и анимации через агента. CX Codex +1 1 300установок ue-materials-rendering quodsoler Помогает писать C++ код материалов и рендеринга для Unreal Engine 5.8: динамические инстансы, коллекции параметров, Render Targets и шейдеры. CX Codex +1 1 200установок

Из того же набора77

phaser-arcade-physics Настраивает перемещение, прыжки и столкновения в 2D-играх на Phaser 4 через физический движок Arcade Physics. Помогает писать контроллеры и собирать группы объектов. CX Codex +1 5 500установок threejs-scene-setup Настраивает базовую сцену three.js и помогает найти причины пустого или чёрного canvas. Нужен при старте проекта, ресайзе, цикле рендеринга и OrbitControls. CX Codex +1 5 500установок threejs-materials-lighting Скилл для three.js: подбирает материал, ставит источники света, включает тени и подключает HDR-окружение, когда модель выглядит чёрной или плоской. CX Codex +1 5 500установок unity-build-pipeline Автоматизирует сборку плееров в Unity 6.3 LTS через BuildPipeline, профили сборки и консольный CI-режим. Помогает выбрать бэкенд и урезать размер билда. CX Codex +1 5 600установок unity-navmesh Скилл для ИИ-кодинга: печёт NavMesh на уровне Unity и водит NPC по маршруту через NavMeshAgent. Пригодится, когда враг должен догонять игрока, а не стоять на месте. CX Codex +1 5 500установок unity-tilemap-2d Помогает собирать и настраивать 2D-тайлмапы в Unity 6.3 LTS через скрипты и Tile Palette. Пригодится при расстановке тайлов, сборке коллайдеров и генерации уровней. CX Codex +1 5 500установок unreal-cpp-gameplay Учит агента писать геймплейный C++ под Unreal Engine 5: макросы рефлексии, классы Gameplay Framework, зависимости модуля в *.Build.cs. CX Codex +1 5 300установок unreal-blueprints Помогает проектировать геймплейную логику на блюпринтах в Unreal Engine 5. Подсказывает, как связать графы событий и не сломать проект жёсткими ссылками при общении классов. CX Codex +1 5 300установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой