大家好,我是前端西瓜哥,今天帶大家看一下 PixiJS 的源碼實作。
PixiJS 是一個非常流行的 Canvas 庫,start 數将近 4w。
使用 PixiJS 簡單易用的 API,我們可以在浏覽器頁面的 Canvas 元素上高性能地繪制圖形,實作流暢的動畫。它的底層是 WebGL。
用 PixiJS 繪制一個矩形,代碼實作為:
const app = new PIXI.Application({
width: 500,
height: 300,
});
document.body.appendChild(app.view);
const graph = new PIXI.Graphics();
graph.beginFill(0xff0044); // 填充色
graph.drawRect(10, 10, 100, 80);
graph.endFill();
app.stage.addChild(graph);
渲染結果:
這些代碼的底層究竟做了什麼呢?這次西瓜哥就帶大家來一探究竟。
使用的 PixiJS 版本為 7.2.4。
Application 的初始化
首先是調用 Application 類的構造函數,建立 app 對象。
下面是 Application 構造函數的代碼。
export class Application {
// 建立 stage
public stage: Container = new Container();
// ...
constructor(options) {
options = Object.assign(
{
// 是否強制使用 Canvas 2D,否則如果支援 WebGL,用 WebGL
// 預設為 false,且已經廢棄 Canvas 2D,僅 pixi.js-legacy 可用
forceCanvas: false,
},
options
);
// 選擇渲染器
this.renderer = autoDetectRenderer(options);
// 插件初始化
Application._plugins.forEach((plugin) => {
plugin.init.call(this, options);
});
}
}
主要做了以下幾件事。
- 初始化 this.stage 為一個新的 Container 對象,将其作為根容器,之後我們繪制的矩形會放置于其下;
- 選擇渲染器 renderer,有兩種:Renderer(基于 WebGL) 和 CanvasRenderer(基于 Canvas 2D)。最新版 PixiJS 隻内置了 Renderer。如果你希望在 WebGL 不可用時回退為 CanvasRenderer,需要改用 pixie.js-legacy 庫。
- 調用 Renderer 的構造函數。它的屬性 view 會指向一個 canvas 元素,Application 的 view 通過 getter 的代理方式拿到這個 view;
- 調用 Application 中注冊插件的 init 方法,進行初始化。
Application 預設内置兩個插件:
- TickerPlugin:不停地在繪制下一幀前調用(基于 requestAnimationFrame)傳入的回調函數,PixiJS 會在這裡指定下一幀數要繪制的新内容;
- ResizePlugin:監聽容器尺寸變化,重繪畫布。
建立圖形
const graph = new PIXI.Graphics();
建立一個 Graphics 對象。這個 Graphics 對象下可以繪制任何圖形,這裡我隻繪制一個矩形。
graph.beginFill(0xff0044); // 填充色
該方法會給 Graphics 對象的 _fillStyle 設定為指定的顔色值。傳入的顔色值會進行标準化(normalize)。
Pixijs 實作有自己的風格:喜歡用類似 _varX 的方法儲存 “私有” 變量,然後提供對應的 setter 和 getter 去讀寫這個内部變量。
getter 可能不提供,這樣一個屬性就會變成隻讀屬性。有些 getter 裡會做懶加載,在第一次讀取的時候再初始化,比如 Texture.WHITE。
如果我們不指定顔色,這個 _fillStyle 會使用預設值,且其 visible 屬性為 false,表示圖形沒有填充色,也會在之後的渲染階段跳過填充的邏輯。
然後是建立一個矩形。
graph.drawRect(10, 10, 100, 80);
上面代碼其實調用的是:
return this.drawShape(new PIXI.Rectangle(x, y, width, height));
首先建立一個 Rectangle 對象。
然後基于該 Rectangle 對象、之前設定的 fillStyle、lineStyle、matrix 建立一個 GraphicsData 對象,最後添加到給 rect._geometry.graphicsData 數組上。
總之就是将這個矩形的資料記錄下來,之後 PixiJS 會基于這些值構造出繪制 WebGL 可以直接使用的資料。
然後是重置填充色。
rect.endFill();
将 rect 的 _fillStyle 設定為預設值:
public reset() {
this.color = 0xFFFFFF;
this.alpha = 1;
this.texture = Texture.WHITE;
this.matrix = null;
this.visible = false;
}
最後是把 rect 添加到容器 app.stage 下。
app.stage.addChild(rect);
對應的源碼是:
export class Container extends DisplayObject {
// ...
addChild(...children) {
if (children.length > 1) {
// 有多個圖形要添加,會周遊調用目前 addChild 方法
for (let i = 0; i < children.length; i++) {
this.addChild(children[i]);
}
} else {
const child = children[0];
if (child.parent) {
child.parent.removeChild(child);
}
child.parent = this;
this.sortDirty = true; // 表示沒有排序
child.transform._parentID = -1;
this.children.push(child);
this._boundsID++;
// 觸發子節點改變的相關事件
this.onChildrenChange(this.children.length - 1);
this.emit("childAdded", child, this, this.children.length - 1);
child.emit("added", this);
}
return children[0];
}
}
至此,我們的矩形設定好屬性并添加到圖形樹上。
下面是渲染環節。
繪制
還記得我們初始化 Application 時,初始化的兩個插件嗎?
其中一個就是 TickerPlugin,它是 raf(requestAnimationFrame)的封裝,會在頁面繪制下一幀要之前執行回調函數。
Application 初始化時,調用了TickerPlugin.init() 方法,将 renderer 的 render 方法綁定到 Ticker 上。這樣,render 就會不斷地被異步調用。
class TickerPlugin {
static init(options) {
Object.defineProperty(this, "ticker", {
set(ticker) {
// 将 app.render 函數傳入 ticker 的回調清單
ticker.add(this.render, this, UPDATE_PRIORITY.LOW);
},
// ...
});
// 觸發 ticker setter
this.ticker = options.sharedTicker ? Ticker.shared : new Ticker();
}
// ...
}
render 方法:
class Application {
// ...
public render() {
this.renderer.render(this.stage);
}
}
因為渲染的過程非常長,代碼邏輯太多,各種細枝末節,這裡隻講大緻流程,之後會寫一篇文章具體講解。
- 遞歸 app.stage 下的子 graph 對象,将其變換矩陣與父容器的做矩陣乘法(父容器的 transfrom 會影響子節點),最終計算出所有節點的最終複合變換矩陣;
- 之前建立的 Rectangle 對象,它的 x、y、width、height,轉換為 WebGL 頂點着色器(Vertex Shader)需要的 8 個頂點資料;
- 對頂點應用變換矩陣;
- 計算好的頂點和顔色的一些中間批量資料。最後在 BatchRenderer.drawBatches() 方法中,調用了 WebGL 的 API:gl.drawElements。
PixiJS 高性能的一個原因是減少 draw call,盡可能一次性批量(batch)提供大量頂點和片元給到 WebGL 去處理,充分利用 GPU 的并發計算能力。
結尾
我是前端西瓜哥,歡迎關注我,學習更多前端知識。