# 交互事件

PixiJS 提供了丰富的事件系统,支持鼠标、触摸和键盘事件。

# 开启交互 {#enable-interaction}

在 PixiJS v8 中,需要设置 eventMode 来启用交互:

const sprite = Sprite.from('button.png');
sprite.eventMode = 'static';  // 启用事件
sprite.cursor = 'pointer';    // 改变光标样式
sprite.on('pointerdown', onClick);
1
2
3
4

# 常用事件 {#common-events}

sprite.eventMode = 'static';

// 鼠标/触摸事件
sprite.on('pointerdown', (e) => console.log('按下'));
sprite.on('pointerup', (e) => console.log('抬起'));
sprite.on('pointermove', (e) => console.log('移动'));
sprite.on('pointerover', (e) => console.log('悬停进入'));
sprite.on('pointerout', (e) => console.log('悬停离开'));
sprite.on('pointertap', (e) => console.log('点击'));  // 兼容移动端
sprite.on('rightclick', (e) => console.log('右键'));
sprite.on('wheel', (e) => console.log('滚轮'));
1
2
3
4
5
6
7
8
9
10
11

# 拖拽实现 {#drag-and-drop}

let isDragging = false;
let offset = { x: 0, y: 0 };

sprite.eventMode = 'static';
sprite.cursor = 'grab';

sprite.on('pointerdown', (e) => {
    isDragging = true;
    sprite.cursor = 'grabbing';
    // 计算点击偏移
    offset.x = e.global.x - sprite.x;
    offset.y = e.global.y - sprite.y;
});

app.stage.on('pointermove', (e) => {
    if (isDragging) {
        sprite.x = e.global.x - offset.x;
        sprite.y = e.global.y - offset.y;
    }
});

app.stage.on('pointerup', () => {
    isDragging = false;
    sprite.cursor = 'grab';
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

# 碰撞检测 {#collision-detection}

function hitTest(r1, r2) {
    return r1.x < r2.x + r2.width
        && r1.x + r1.width > r2.x
        && r1.y < r2.y + r2.height
        && r1.y + r1.height > r2.y;
}
1
2
3
4
5
6

# 事件冒泡 {#event-bubbling}

PixiJS 事件遵循类似 DOM 的冒泡机制:

container.eventMode = 'static';
child.eventMode = 'static';

child.on('pointerdown', (e) => {
    console.log('子元素先触发');
    e.stopPropagation(); // 阻止冒泡
});

container.on('pointerdown', () => {
    console.log('容器后触发(如果未阻止冒泡)');
});
1
2
3
4
5
6
7
8
9
10
11

# 在线 Demo {#online-demo}