PixiJS 學習:設置圖形的光標樣式
大家好,我是前端西瓜哥。
最近又要開始學習 pixijs 了。
今天我們來學習如何給 pixijs 的圖形設置光標(cursor)。
pixijs 版本為 7.4.2
首先我們先用 pixijs 繪制好一個橢圓和一個矩形。
import { Application, Graphics } from'pixi.js';
const app = new Application({
width: 500,
height: 400,
antialias: true,
backgroundColor: 0xffffff,
});
const ellipse = new Graphics()
.beginFill(0xff0044)
.drawEllipse(130, 100, 60, 30)
.endFill();
const rect = new Graphics()
.beginFill(0x0000ff)
.drawRect(200, 150, 60, 40)
.endFill();
app.stage.addChild(ellipse, rect);
document.body.appendChild(app.view);
渲染結果為:
設置光標
我們先給 ellipse 設置為可交互,這樣圖形才能激活 hitTest 功能和觸發(fā)事件。
ellipse.eventMode = 'static';
// ellipse.interactive = true; // 這個廢棄了
然后設置 cursor 為 pointer。
ellipse.cursor = 'pointer';
看看效果:
原理是鼠標移動時會進行 hitTest,當橢圓的 hitTest 為 true 時,將 canvas 畫布元素的 style 的 cursor 屬性設置為橢圓對應的 cursor,即 "pointer"。
當鼠標移出橢圓時,canvas 的 cursor 值會恢復為默認的 "inherit"。
矩形因為沒設置為可交互,所以沒有任何反應。
設置自定義光標
一般來說,pixijs 只是會將 canvas 的 cursor 改為對應的字符串值,比如 "default"。
但我們可以全局配置 app.renderer.events.cursorStyles,重新定義 "default" 為我們自定義的光標圖片。
app.renderer.events.cursorStyles.default =
'url(./suika-cursor-default.png) 5 5, auto';
app.renderer.events.cursorStyles.pointer =
'url(./suika-cursor-move.png) 16 16, auto';
語法同 CSS 的 cursor。
效果:
其實就是更新了一個映射表,當 pixijs 要設置圖形的 cursor 值時,如果發(fā)現(xiàn)映射表中作為 key 有映射值,會改為使用映射值;否則直接使用圖形的 cursor 值。