iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 23
0
Modern Web

再談 PixiJS,那些先前不一定有提到的部分與地雷系列 第 23

[Re:PixiJS - Day23] 了解 Texture / BaseTexture

這篇介紹 Texture / BaseTexture
好像常看到他們,可是有不是很好理解

可以想像 TextureSprite 使用的材質,那 BaseTexture 是...?


從讀入 Sprite 的過程來理解 Texture

使用 Sprite 物件的時候,會把讀入的圖片變成 Texture / BaseTexture 使用

SPRITE - Basic 例子舉例:

const bunny = PIXI.Sprite.from('assets/basics/bunny.png');
app.stage.addChild(bunny);

可透過 PIXI.utils.TextureCachePIXI.utils.BaseTextureCache 觀察 PIXI 裡 TextureBaseTextureCache快取狀態

雖然 key值 相同,但 TextureBaseTexture不同的東西


放入很多兔子:

在一開始讀入後,便會有兔子的 Texture / BaseTexture 快取
因此再次使用的時候不會再存到快取內

[ Demo ]:

function createBunny(){
	const bunny = PIXI.Sprite.from('assets/basics/bunny.png');

	bunny.x = Math.random() * app.screen.width;
	bunny.y = Math.random() * app.screen.height;
	app.stage.addChild(bunny);
};

for(let i = 0; i<50; i++){
	createBunny();
};

檢查快取:

PIXI.utils.TextureCache:一個,assets/basics/bunny.png
PIXI.utils.BaseTextureCache:一個,assets/basics/bunny.png

不會再發 Request

Sprite.from() 的補充:

範例裡 PIXI.Sprite.from()new PIXI.Sprite() 方法看起來很類似,
實際上也是相同的 - PIXI.Sprite.from()

static from(source, options) {
    const texture = (source instanceof Texture)
        ? source
        : Texture.from(source, options);
    return new Sprite(texture);
}

從建構式來看 Texture 與 BaseTexture:

PIXI.Texture

PIXI.Texture 的建構式會傳入 BaseTexture

並可從 Texture 實體取得相對應的 BaseTexture

由於有這樣的關係,因此 不同的 Texture 可以有 相同的 BaseTexture


各種測試:

1. 不同方式讀入同一張圖片

讀入時會檢查快取,由於路徑相同 - TextureBaseTexture 相同。

const bunny = PIXI.Sprite.from('assets/basics/bunny.png');
const texture1 = PIXI.Texture.from('assets/basics/bunny.png');

console.log(bunny.texture === texture1);
// true

console.log(bunny.texture.baseTexture === texture1.baseTexture);
// true

2. 讀入的網址不同時:

網址不同,快取位置不同 - TextureBaseTexture 皆不相同。

const texture1 = PIXI.Texture.from('assets/basics/bunny.png');
const texture2 = PIXI.Texture.from('assets/basics/bunny.png?v=2');

console.log(texture2 === texture1);
// false

console.log(texture2.baseTexture === texture1.baseTexture);
// false

3. 使用 new Texture() 建立 Texture,放的是同一個 BaseTexture

Texture 不同,BaseTexture 相同

const testBaseTexture = new PIXI.BaseTexture('assets/basics/bunny.png?v=3');
const texture3 = new PIXI.Texture(testBaseTexture);
const texture4 = new PIXI.Texture(testBaseTexture);
console.log(texture4 === texture3);
// false

console.log(texture4.baseTexture === texture3.baseTexture);
// true

[ Demo ]


另一個 texturebaseTexture 不同的情形:

使用 spriteSheet 時,
PixiJS 會依據 JSON 裡面的物件,將每個部分的圖檔生成一個 Texture,但 BaseTexture同一個

[ Demo] :

參考討論:

Difference between texture and baseTexture?


上一篇
[Re:PixiJS - Day22] 畫漸層線段、材質問題
下一篇
[Re:PixiJS - Day24] 用 Texture 實作把網頁弄壞 的 Demo
系列文
再談 PixiJS,那些先前不一定有提到的部分與地雷45
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言