# Sprite 与纹理

Sprite 是 PixiJS 中最常用的显示对象,用于显示图片。

# 加载纹理 {#loading-textures}

PixiJS v8 使用 Assets 模块来加载图片资源:

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

const app = new Application();
await app.init({ width: 800, height: 600 });
document.body.appendChild(app.canvas);

// 加载单张图片
const texture = await Assets.load('images/logo.png');
const sprite = Sprite.from(texture);
app.stage.addChild(sprite);
1
2
3
4
5
6
7
8
9
10

# 批量加载 {#batch-loading}

// 批量加载并设置别名
await Assets.load([
    { alias: 'bg', src: 'images/background.jpg' },
    { alias: 'player', src: 'images/player.png' },
    { alias: 'enemy', src: 'images/enemy.png' },
]);

// 通过别名引用
const bg = Sprite.from('bg');
const player = Sprite.from('player');
1
2
3
4
5
6
7
8
9
10

# Sprite 变换属性 {#sprite-transform}

sprite.x = 100;            // X 轴位置
sprite.y = 200;            // Y 轴位置
sprite.rotation = 0.5;     // 弧度旋转
sprite.scale.x = 2;        // X 轴缩放
sprite.scale.y = 2;        // Y 轴缩放
sprite.alpha = 0.8;        // 透明度 0-1
sprite.anchor.set(0.5);    // 锚点(中心点)
sprite.visible = true;     // 可见性
sprite.width = 300;        // 设置宽度(等比缩放)
1
2
3
4
5
6
7
8
9

# 锚点(Anchor) {#anchor}

锚点决定了 Sprite 的"原点"位置:

// 锚点范围 0-1,相对于 Sprite 自身尺寸
sprite.anchor.set(0.5, 0.5);   // 中心点
sprite.anchor.set(0, 0);       // 左上角(默认)
sprite.anchor.set(1, 1);       // 右下角
1
2
3
4

# 纹理图集(Spritesheet) {#texture-atlas}

使用纹理图集可以显著提升渲染性能:

// 加载图集 JSON
const atlas = await Assets.load('assets/spritesheet.json');

// 通过帧名称创建 Sprite
const frame1 = Sprite.from('walk01');
const frame2 = Sprite.from('walk02');
1
2
3
4
5
6

# 纹理缓存 {#texture-cache}

PixiJS 会自动缓存已加载的纹理,重复使用不会重复加载:

// 只有第一次会真正加载
const tex1 = await Assets.load('images/icon.png');
const tex2 = await Assets.load('images/icon.png'); // 从缓存读取

console.log(tex1 === tex2); // true
1
2
3
4
5

# 在线 Demo {#online-demo}