Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(render): TextureCanvas — a blank texture textures are pasted into at pixel positions, then shown on a Sprite; with an example and docs

yhhdd6e258caf12
diff --git a/docs/astro/src/content/docs/graphics/drawing.mdx b/docs/astro/src/content/docs/graphics/drawing.mdx
index 4df2a728c..e39400550 100644
--- a/docs/astro/src/content/docs/graphics/drawing.mdx
+++ b/docs/astro/src/content/docs/graphics/drawing.mdx
@@ -294,6 +294,36 @@ too (`x`, `y` from the top, `width`, `height`).
The [Render Texture example](https://github.com/esengine/estella/tree/master/examples/render-texture)
builds four cards and packs them (`src/systems/atlas.ts`).
+## Composing a picture at known positions: `TextureCanvas`
+
+When you already know where each piece goes — a character built from parts, a card with an icon and a
+frame — make a blank canvas, paste textures into it, and put the result on a `Sprite`. It is the same
+idea as Unity's `Graphics.CopyTexture` or drawing onto an Unreal render target.
+
+```typescript
+import { TextureCanvas } from 'esengine';
+
+// In a system in Schedule.Update — each draw is a pass of its own.
+const canvas = TextureCanvas.create(256, 256); // 1. a blank, transparent canvas
+if (!canvas) return; // the renderer is not up yet: try again next frame
+canvas.draw(body, 96, 100); // 2. paste: (x, y) is the picture's top-left corner
+canvas.draw(head, 104, 46);
+canvas.draw(head, 190, 20, 24, 24); // optional width and height scale it
+world.insert(entity, Sprite, { texture: canvas.texture, size: { x: 512, y: 512 } }); // 3. show it
+```
+
+- `x` and `y` count pixels from the canvas's top-left, y pointing down. The picture is drawn at its
+ own size unless you give `width` and `height`.
+- Pictures blend over what is already there, in the order you paste them.
+- `canvas.clear()` makes it transparent again; `canvas.release()` frees it.
+- **Keep the pasted textures alive.** After a lost graphics device the canvas is drawn again from
+ them, in the same order, automatically.
+- The canvas is an ordinary texture — show it with no `flipY`. For pictures you have no positions for,
+ `TextureAtlas.pack` lays them out for you.
+
+The [Texture Canvas example](https://github.com/esengine/estella/tree/master/examples/texture-canvas)
+builds a small figure from seven pastes.
+
## See also
- [Sprites & Rendering](/docs/graphics/sprites/) — the component path for images and shapes.
diff --git a/docs/astro/src/content/docs/zh-cn/graphics/drawing.mdx b/docs/astro/src/content/docs/zh-cn/graphics/drawing.mdx
index a6667984f..217b3e5cf 100644
--- a/docs/astro/src/content/docs/zh-cn/graphics/drawing.mdx
+++ b/docs/astro/src/content/docs/zh-cn/graphics/drawing.mdx
@@ -271,6 +271,32 @@ world.insert(entity, Sprite, { ...atlas.sprite(iconB), size: { x: 64, y: 64 } })
[Render Texture 示例](https://github.com/esengine/estella/tree/master/examples/render-texture)
里建了四张卡片并打包(`src/systems/atlas.ts`)。
+## 按指定位置拼一张图:`TextureCanvas`
+
+已经知道每一块放在哪里时(由部件拼成的角色、带图标和边框的卡片),先建一块空白画布,把纹理贴进去,
+再把成品放到 `Sprite` 上。思路与 Unity 的 `Graphics.CopyTexture`、往 UE 的 RenderTarget 上绘制相同。
+
+```typescript
+import { TextureCanvas } from 'esengine';
+
+// 在 Schedule.Update 的系统里——每次 draw 都是一个独立的渲染 pass。
+const canvas = TextureCanvas.create(256, 256); // 1. 空白透明画布
+if (!canvas) return; // 渲染器还没起来:下一帧再试
+canvas.draw(body, 96, 100); // 2. 贴图:(x, y) 是这张图的左上角
+canvas.draw(head, 104, 46);
+canvas.draw(head, 190, 20, 24, 24); // 可选的 width、height 用来缩放
+world.insert(entity, Sprite, { texture: canvas.texture, size: { x: 512, y: 512 } }); // 3. 显示
+```
+
+- `x`、`y` 以画布左上角为原点、单位像素、y 向下。不给 `width`、`height` 就按图片自身大小绘制。
+- 后贴的盖在先贴的上面,透明部分会混合。
+- `canvas.clear()` 清回透明,`canvas.release()` 释放。
+- **被贴的纹理要保持存活。** 图形设备丢失后,画布会按原顺序自动重画。
+- 画布就是普通纹理,显示时不要加 `flipY`。没有现成位置、想让引擎自动排布时,用 `TextureAtlas.pack`。
+
+[Texture Canvas 示例](https://github.com/esengine/estella/tree/master/examples/texture-canvas)
+用七次贴图拼出一个小人。
+
## 参见
- [精灵与渲染](/docs/zh-cn/graphics/sprites/) —— 图像与形状的组件路径。
diff --git a/examples/README.md b/examples/README.md
index 16cf2cc52..f65395f97 100644
--- a/examples/README.md
+++ b/examples/README.md
@@ -39,6 +39,7 @@ for your own game.
| **lighting-2d** | Rendering | Dynamic 2D lights and soft shadow casters over `Sprite.lit` surfaces. |
| **effects-gallery** | Rendering | The built-in material effect templates — hit flash, outline, dissolve, pixelate, UV scroll — with params driven from code. |
| **render-texture** | Rendering | Render-to-texture — a live minimap painted with the `Draw` API into a `RenderTexture`, resolution cycling on R. |
+| **texture-canvas** | Rendering | Compose a picture at run time — a blank `TextureCanvas`, textures pasted in at pixel positions, the result shown on a `Sprite`. |
| **drawing-demo** | Rendering | The three drawing tiers — immediate `Draw` radar overlay, retained `Graphics` vector star, procedural `Mesh2D` ribbon. |
| **wilds** | Rendering | A lake under mountains at dusk — a generated `Terrain` from a heightmap, `Water` with measured depth and shore foam, `Foliage` grass and pines swaying in the wind, and clouds that cast shadows. Everything is made from numbers by `tools/build.mjs`. |
| **worldgen** | Rendering | A world laid out by rules as you walk through it — `WorldGen` biomes, groves and rock groups composed by recipe, copper to mine, `WorldZone`s keeping a home and a road clear, over ground without end. |
diff --git a/examples/texture-canvas/.gitignore b/examples/texture-canvas/.gitignore
new file mode 100644
index 000000000..359472ac2
--- /dev/null
+++ b/examples/texture-canvas/.gitignore
@@ -0,0 +1,7 @@
+node_modules/
+dist/
+.vscode/
+.idea/
+.DS_Store
+Thumbs.db
+.esengine/cache/
diff --git a/examples/texture-canvas/README.md b/examples/texture-canvas/README.md
new file mode 100644
index 000000000..6e491a5b1
--- /dev/null
+++ b/examples/texture-canvas/README.md
@@ -0,0 +1,39 @@
+# Texture Canvas
+
+Compose a picture at run time: make a blank canvas, paste textures into it at pixel positions,
+and show the result on a `Sprite`. The same three steps as Unity's `Graphics.CopyTexture` or
+drawing onto an Unreal render target, in `src/main.ts`:
+
+```typescript
+const canvas = TextureCanvas.create(256, 256); // 1. a blank canvas
+canvas.draw(body.texture, 96, 100); // 2. paste a texture: (x, y) = its top-left corner
+canvas.draw(head.texture, 104, 46);
+canvas.draw(head.texture, 190, 20, 24, 24); // optional width and height scale it
+sprite.texture = canvas.texture; // 3. the finished texture goes on a Sprite
+```
+
+A small figure is put together from a body, a head, two arms and two legs, plus a smaller head
+pasted off to the side. The parts are painted flat-coloured textures so the example needs no asset
+files; in a game they would be loaded images.
+
+- **Coordinates** are pixels from the canvas's top-left, y pointing down, like an image editor.
+- **Order matters**: pictures blend over what is already there, in the order they are pasted. The
+ legs go first so the body covers their tops.
+- **Call it from a `Schedule.Update` system**, not a draw callback: each `draw` is a render pass of
+ its own.
+- **Keep the pasted textures alive.** After a lost graphics device the canvas is drawn again from
+ them, in the same order, automatically.
+- `canvas.clear()` turns it transparent again; `canvas.release()` frees it.
+- To pack many pictures with no positions of your own, use `TextureAtlas.pack` instead
+ (see the [Render Texture example](../render-texture)).
+
+## 中文摘要
+
+在运行时拼一张图:先建一块空白画布,再把纹理按像素坐标贴进去,最后把成品纹理赋给 `Sprite`。
+对应 Unity 的 `Graphics.CopyTexture`、UE 往 RenderTarget 上绘制,代码见 `src/main.ts`。
+
+- 坐标以画布左上角为原点、y 向下(像素)。
+- 后贴的盖在先贴的上面。
+- 在 `Schedule.Update` 的系统里调用,不要放进 draw callback。
+- 被贴的纹理要保持存活:设备丢失后会按原顺序自动重画。
+- 想要引擎自动排布、不指定位置,用 `TextureAtlas.pack`。
diff --git a/examples/texture-canvas/assets/scenes/main.esscene b/examples/texture-canvas/assets/scenes/main.esscene
new file mode 100644
index 000000000..b558d6484
--- /dev/null
+++ b/examples/texture-canvas/assets/scenes/main.esscene
@@ -0,0 +1,34 @@
+{
+ "version": 4,
+ "name": "Main",
+ "entities": [
+ {
+ "id": 0,
+ "name": "Camera",
+ "parent": null,
+ "children": [],
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 10
+ }
+ }
+ },
+ {
+ "type": "Camera",
+ "data": {
+ "projectionType": 1,
+ "orthoSize": 360,
+ "isActive": true,
+ "priority": 0
+ }
+ }
+ ],
+ "visible": true
+ }
+ ]
+}
diff --git a/examples/texture-canvas/assets/scenes/main.esscene.meta b/examples/texture-canvas/assets/scenes/main.esscene.meta
new file mode 100644
index 000000000..9ae09f826
--- /dev/null
+++ b/examples/texture-canvas/assets/scenes/main.esscene.meta
@@ -0,0 +1,8 @@
+{
+ "uuid": "12e9af34-5dcd-4782-b0d2-12c16ae41ad7",
+ "version": "2.0",
+ "type": "scene",
+ "importer": {
+ "autoMigrate": true
+ }
+}
\ No newline at end of file
diff --git a/examples/texture-canvas/project.esproject b/examples/texture-canvas/project.esproject
new file mode 100644
index 000000000..b14b10d5b
--- /dev/null
+++ b/examples/texture-canvas/project.esproject
@@ -0,0 +1,13 @@
+{
+ "formatVersion": "1",
+ "name": "Texture Canvas",
+ "description": "Compose a picture at run time: make a blank TextureCanvas, paste textures into it at pixel positions, and show the result on a Sprite.",
+ "tag": "Rendering",
+ "version": "1.0.0",
+ "defaultScene": "assets/scenes/main.esscene",
+ "designResolution": {
+ "width": 1280,
+ "height": 720
+ },
+ "spineVersion": "none"
+}
\ No newline at end of file
diff --git a/examples/texture-canvas/src/main.ts b/examples/texture-canvas/src/main.ts
new file mode 100644
index 000000000..0605a8306
--- /dev/null
+++ b/examples/texture-canvas/src/main.ts
@@ -0,0 +1,58 @@
+// Texture Canvas: make a blank canvas, paste textures into it at pixel positions, show the result on a Sprite.
+import {
+ addSystemToSchedule, defineSystem, Commands, Transform, Sprite, Schedule,
+ RenderTexture, Renderer, Draw, BlendMode, TextureCanvas,
+ type RenderTextureHandle,
+} from 'esengine';
+
+type Color = { r: number; g: number; b: number; a: number };
+
+// The parts. In a game these would be loaded images (what `Sprite.texture` holds); here each is a
+// flat-coloured texture painted on the spot so the example needs no asset files.
+function solid(width: number, height: number, color: Color): RenderTextureHandle {
+ const rt = RenderTexture.create({ width, height, depth: false, filter: 'nearest' });
+ const vp = new Float32Array(16);
+ vp[0] = 2 / width; vp[5] = 2 / height; vp[10] = -1; vp[12] = -1; vp[13] = -1; vp[15] = 1;
+ RenderTexture.begin(rt, vp);
+ Draw.begin(vp);
+ Renderer.setViewport(0, 0, width, height);
+ Draw.setBlendMode(BlendMode.None);
+ Draw.rect({ x: width / 2, y: height / 2 }, { x: width, y: height }, color);
+ Draw.end();
+ RenderTexture.end();
+ RenderTexture.contentDrawn(rt);
+ return rt;
+}
+
+let composed = false;
+
+const composeSystem = defineSystem([Commands()], (cmds) => {
+ if (composed) return;
+
+ // 1. A blank 256 x 256 canvas.
+ const canvas = TextureCanvas.create(256, 256, { filter: 'nearest' });
+ if (!canvas) return; // the renderer is not up yet: try again next frame
+
+ const body = solid(64, 96, { r: 0.35, g: 0.6, b: 0.95, a: 1 });
+ const head = solid(48, 48, { r: 0.98, g: 0.8, b: 0.6, a: 1 });
+ const arm = solid(20, 72, { r: 0.3, g: 0.5, b: 0.85, a: 1 });
+ const leg = solid(26, 60, { r: 0.25, g: 0.3, b: 0.5, a: 1 });
+
+ // 2. Paste textures in. (x, y) is the picture's top-left corner, counted in pixels from the canvas's top-left.
+ canvas.draw(leg.texture, 88, 190);
+ canvas.draw(leg.texture, 142, 190);
+ canvas.draw(body.texture, 96, 100);
+ canvas.draw(arm.texture, 68, 104);
+ canvas.draw(arm.texture, 168, 104);
+ canvas.draw(head.texture, 104, 46);
+ canvas.draw(head.texture, 190, 20, 24, 24); // optional width and height scale a picture as it is pasted
+
+ // 3. The canvas is an ordinary texture: give it to a Sprite.
+ cmds.spawn()
+ .insert(Transform, { position: { x: 0, y: 0, z: 0 } })
+ .insert(Sprite, { texture: canvas.texture, size: { x: 512, y: 512 }, color: { r: 1, g: 1, b: 1, a: 1 } });
+
+ composed = true;
+}, { name: 'ComposeSystem' });
+
+addSystemToSchedule(Schedule.Update, composeSystem);
diff --git a/examples/texture-canvas/tsconfig.json b/examples/texture-canvas/tsconfig.json
new file mode 100644
index 000000000..105dd19fa
--- /dev/null
+++ b/examples/texture-canvas/tsconfig.json
@@ -0,0 +1,21 @@
+{
+ "compilerOptions": {
+ "target": "ES2020",
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "strict": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "forceConsistentCasingInFileNames": true,
+ "declaration": false,
+ "outDir": "./dist",
+ "rootDir": ".",
+ "paths": {
+ "esengine": ["./.esengine/sdk/index.d.ts"],
+ "estella-plugin-*": ["./.esengine/packages/*"],
+ "esengine/wasm": ["./.esengine/sdk/wasm.d.ts"]
+ }
+ },
+ "include": ["src/**/*"],
+ "exclude": ["node_modules"]
+}
diff --git a/sdk/src/core-render.ts b/sdk/src/core-render.ts
index cfd75a0c4..a67113890 100644
--- a/sdk/src/core-render.ts
+++ b/sdk/src/core-render.ts
@@ -315,6 +315,12 @@ export {
type AtlasEntry,
} from './render/textureAtlas';
+export {
+ TextureCanvas,
+ type TextureCanvasHandle,
+ type TextureCanvasOptions,
+} from './render/textureCanvas';
+
// =============================================================================
// Render Pipeline
// =============================================================================
diff --git a/sdk/src/render/textureCanvas.ts b/sdk/src/render/textureCanvas.ts
new file mode 100644
index 000000000..c6a209002
--- /dev/null
+++ b/sdk/src/render/textureCanvas.ts
@@ -0,0 +1,137 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file textureCanvas.ts
+ * @brief A blank texture you paste other textures into at pixel positions — compose a picture at run time, then show it on a Sprite.
+ */
+import { Draw } from './draw';
+import { BlendMode } from './blend';
+import { Renderer, onDeviceRestored } from './renderer';
+import { RenderTexture, type RenderTextureHandle } from './renderTexture';
+import { getResourceManager, getTextureDimensions } from '../wasm/resourceManager';
+import { log } from '../util/logger';
+
+/** Options of {@link TextureCanvas.create}. @experimental */
+export interface TextureCanvasOptions {
+ /** Sampling filter when the canvas is shown. Default `'linear'`; `'nearest'` for pixel art. */
+ filter?: 'nearest' | 'linear';
+}
+
+/** A canvas you can paste textures into. @experimental */
+export interface TextureCanvasHandle {
+ /** Resource-table handle of the canvas — what `Sprite.texture` takes. Show it with no `flipY`. */
+ readonly texture: number;
+ readonly width: number;
+ readonly height: number;
+ /**
+ * Pastes `source` (a texture handle) with its top-left corner at (`x`, `y`), counted in pixels from the
+ * canvas's top-left. It is drawn at its own size unless `width` and `height` are given. Pictures blend over
+ * what is already there, in the order they are pasted.
+ */
+ draw(source: number, x: number, y: number, width?: number, height?: number): void;
+ /** Back to transparent, forgetting everything pasted. */
+ clear(): void;
+ /** Frees the canvas. The pasted textures are not touched. */
+ release(): void;
+}
+
+interface Paste {
+ source: number;
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
+/** Column-major orthographic projection with pixel units, origin at the bottom-left. */
+function pixelProjection(width: number, height: number): Float32Array {
+ const m = new Float32Array(16);
+ m[0] = 2 / width;
+ m[5] = 2 / height;
+ m[10] = -1;
+ m[12] = -1;
+ m[13] = -1;
+ m[15] = 1;
+ return m;
+}
+
+export const TextureCanvas = {
+ /**
+ * A transparent canvas `width` × `height` pixels. Call it, and `draw`, from a `Schedule.Update` system, not a
+ * draw callback: each paste is a pass of its own. Null while the renderer is not up yet. Keep the pasted
+ * textures alive: a device loss pastes them again.
+ * @experimental
+ */
+ create(width: number, height: number, options: TextureCanvasOptions = {}): TextureCanvasHandle | null {
+ if (!(width > 0) || !(height > 0)) throw new Error(`a canvas needs a size, got ${width}×${height}`);
+ const rt: RenderTextureHandle = RenderTexture.create({ width, height, depth: false, filter: options.filter ?? 'linear' });
+ if (rt.texture === 0) {
+ RenderTexture.release(rt);
+ return null;
+ }
+
+ const pastes: Paste[] = [];
+ const projection = pixelProjection(width, height);
+
+ const paint = (draws: (rm: ReturnType<typeof getResourceManager>) => void): void => {
+ RenderTexture.begin(rt, projection);
+ Draw.begin(projection);
+ Renderer.setViewport(0, 0, width, height);
+ draws(getResourceManager());
+ Draw.end();
+ RenderTexture.end();
+ RenderTexture.contentDrawn(rt);
+ };
+ const blank = (): void => {
+ Draw.setBlendMode(BlendMode.None);
+ Draw.rect({ x: width / 2, y: height / 2 }, { x: width, y: height }, { r: 1, g: 1, b: 1, a: 0 });
+ };
+ // Pixels count from the top of the canvas, the projection from its bottom; the device id is asked afresh
+ // each time because a device loss renumbers it.
+ const paste = (rm: ReturnType<typeof getResourceManager>, p: Paste): void => {
+ const deviceId = rm?.getTextureGLId(p.source) ?? 0;
+ if (deviceId === 0) return;
+ Draw.setBlendMode(BlendMode.Normal);
+ Draw.texture({ x: p.x + p.width / 2, y: height - p.y - p.height / 2 }, { x: p.width, y: p.height }, deviceId);
+ };
+
+ paint(blank);
+ const unsubscribe = onDeviceRestored(() => {
+ try {
+ paint((rm) => {
+ blank();
+ for (const p of pastes) paste(rm, p);
+ });
+ } catch (error) {
+ log.warn('textureCanvas', `the canvas cannot be drawn again after the device came back: ${String(error)}`);
+ }
+ });
+
+ return {
+ texture: rt.texture,
+ width,
+ height,
+ draw(source, x, y, w, h) {
+ let drawnWidth = w;
+ let drawnHeight = h;
+ if (drawnWidth === undefined || drawnHeight === undefined) {
+ const dims = getTextureDimensions(source);
+ if (!dims || dims.width <= 0 || dims.height <= 0) throw new Error(`texture handle ${source} has no size to draw`);
+ drawnWidth ??= dims.width;
+ drawnHeight ??= dims.height;
+ }
+ const p: Paste = { source, x, y, width: drawnWidth, height: drawnHeight };
+ pastes.push(p);
+ paint((rm) => paste(rm, p));
+ },
+ clear() {
+ pastes.length = 0;
+ paint(blank);
+ },
+ release() {
+ unsubscribe();
+ RenderTexture.release(rt);
+ },
+ };
+ },
+};
diff --git a/sdk/tests/textureCanvas.test.ts b/sdk/tests/textureCanvas.test.ts
new file mode 100644
index 000000000..139c65829
--- /dev/null
+++ b/sdk/tests/textureCanvas.test.ts
@@ -0,0 +1,92 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The texture canvas: a blank texture textures are pasted into at pixel positions from its top-left, and drawn again after a lost device.
+ */
+import { describe, expect, it, vi, beforeEach } from 'vitest';
+
+const drawn: Array<{ pos: { x: number; y: number }; size: { x: number; y: number }; id: number }> = [];
+const created: Array<{ width: number; height: number }> = [];
+let restored: (() => void) | null = null;
+let texture = 500;
+
+vi.mock('../src/render/draw', () => ({
+ Draw: {
+ begin: vi.fn(), end: vi.fn(), setBlendMode: vi.fn(), rect: vi.fn(),
+ texture: (pos: { x: number; y: number }, size: { x: number; y: number }, id: number) => { drawn.push({ pos, size, id }); },
+ },
+}));
+vi.mock('../src/render/renderer', () => ({
+ deviceGeneration: () => 1,
+ Renderer: { setViewport: vi.fn() },
+ onDeviceRestored: (fn: () => void) => { restored = fn; return () => { restored = null; }; },
+}));
+vi.mock('../src/render/renderTexture', () => ({
+ RenderTexture: {
+ create: vi.fn((o: { width: number; height: number }) => { created.push(o); return { texture, width: o.width, height: o.height }; }),
+ release: vi.fn(), begin: vi.fn(), end: vi.fn(), contentDrawn: vi.fn(),
+ },
+}));
+const dims = new Map<number, { width: number; height: number }>();
+vi.mock('../src/wasm/resourceManager', () => ({
+ getTextureDimensions: (h: number) => dims.get(h) ?? null,
+ getResourceManager: () => ({ getTextureGLId: (h: number) => h + 1000 }),
+}));
+
+import { TextureCanvas } from '../src/render/textureCanvas';
+
+describe('TextureCanvas', () => {
+ beforeEach(() => {
+ drawn.length = 0;
+ created.length = 0;
+ dims.clear();
+ dims.set(1, { width: 64, height: 32 });
+ dims.set(2, { width: 16, height: 16 });
+ texture = 500;
+ });
+
+ it('is the size asked for, and hands out the texture a Sprite takes', () => {
+ const canvas = TextureCanvas.create(256, 128)!;
+ expect([canvas.width, canvas.height, canvas.texture]).toEqual([256, 128, 500]);
+ expect(created).toEqual([{ width: 256, height: 128, depth: false, filter: 'linear' }]);
+ });
+
+ it('puts a picture with its top-left corner at (x, y) counted from the top, at its own size', () => {
+ const canvas = TextureCanvas.create(256, 128)!;
+ canvas.draw(1, 10, 20);
+ expect(drawn).toEqual([{ pos: { x: 10 + 32, y: 128 - 20 - 16 }, size: { x: 64, y: 32 }, id: 1001 }]);
+ });
+
+ it('draws a stated size instead of the picture\'s own', () => {
+ const canvas = TextureCanvas.create(100, 100)!;
+ canvas.draw(2, 0, 0, 50, 30);
+ expect(drawn[0].size).toEqual({ x: 50, y: 30 });
+ expect(drawn[0].pos).toEqual({ x: 25, y: 100 - 15 });
+ });
+
+ it('draws everything pasted again when the device comes back, in order, and not what clear forgot', () => {
+ const canvas = TextureCanvas.create(256, 128)!;
+ canvas.draw(1, 0, 0);
+ canvas.draw(2, 70, 0);
+ drawn.length = 0;
+ restored!();
+ expect(drawn.map((d) => d.id)).toEqual([1001, 1002]);
+ canvas.clear();
+ drawn.length = 0;
+ restored!();
+ expect(drawn).toHaveLength(0);
+ });
+
+ it('stops listening once released', () => {
+ TextureCanvas.create(8, 8)!.release();
+ expect(restored).toBeNull();
+ });
+
+ it('says so for a handle with no size and a canvas with none, and is null while the renderer is not up', () => {
+ const canvas = TextureCanvas.create(64, 64)!;
+ expect(() => canvas.draw(99, 0, 0)).toThrow(/no size/);
+ expect(() => TextureCanvas.create(0, 64)).toThrow(/needs a size/);
+ texture = 0;
+ expect(TextureCanvas.create(64, 64)).toBeNull();
+ });
+});