1.6 事件交互
實現要求:點擊寶劍,修改寶劍的顏色。
1??實現代碼:
// 為精靈添加交互事件
sprite.interactive = true;
sprite.on('click', () => {// 點擊精靈時,改變精靈的顏色sprite.tint = Math.random() * 0xFFFFFF;
});
說明:
- 在 PixiJS 中,
sprite.tint
是一個用于改變精靈(Sprite)顏色的屬性。它通過乘法混合的方式將指定的顏色應用到精靈的原始紋理上,從而實現變色效果。
2??實現效果:
3??完整代碼:
<template>
<div></div>
</template><script setup>
// 導入pixi.js
import * as PIXI from 'pixi.js';
// 創建應用
const app = new PIXI.Application({width: window.innerWidth,height: window.innerHeight,backgroundColor: 0x1099bb,resolution: window.devicePixelRatio || 1,// 設置抗鋸齒antialias: true
})
// 將應用畫布添加到DOM中
document.body.appendChild(app.view);// 創建一個紋理
const texture = PIXI.Texture.from('./textures/mujian.png');
// 創建一個精靈
const sprite = new PIXI.Sprite(texture);
// 設置精靈的錨點
sprite.anchor.set(0.5, 0.5);
// 設置精靈的位置
sprite.position.set(window.innerWidth / 2, window.innerHeight / 2);
// 設置精靈的縮放
sprite.scale.set(0.5, 0.5);
// 設置精靈的旋轉
sprite.rotation = 0.5;
// 將精靈添加到舞臺
app.stage.addChild(sprite);// ticker實現動畫
app.ticker.add((delta) => {// 每幀旋轉精靈sprite.rotation += 0.01 * delta;
});// 為精靈添加交互事件
sprite.interactive = true;
sprite.on('click', () => {// 點擊精靈時,改變精靈的顏色sprite.tint = Math.random() * 0xFFFFFF;
});</script><style>
*{margin: 0;padding: 0;box-sizing: border-box;
}
canvas{width: 100vw;height: 100vh;position: fixed;left: 0;top: 0;
}
</style>