PixiJS 學(xué)習(xí):設(shè)置圖形的光標(biāo)樣式
大家好,我是前端西瓜哥。
最近又要開(kāi)始學(xué)習(xí) pixijs 了。
今天我們來(lái)學(xué)習(xí)如何給 pixijs 的圖形設(shè)置光標(biāo)(cursor)。
pixijs 版本為 7.4.2
首先我們先用 pixijs 繪制好一個(gè)橢圓和一個(gè)矩形。
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);
渲染結(jié)果為:
設(shè)置光標(biāo)
我們先給 ellipse 設(shè)置為可交互,這樣圖形才能激活 hitTest 功能和觸發(fā)事件。
ellipse.eventMode = 'static';
// ellipse.interactive = true; // 這個(gè)廢棄了
然后設(shè)置 cursor 為 pointer。
ellipse.cursor = 'pointer';
看看效果:
原理是鼠標(biāo)移動(dòng)時(shí)會(huì)進(jìn)行 hitTest,當(dāng)橢圓的 hitTest 為 true 時(shí),將 canvas 畫(huà)布元素的 style 的 cursor 屬性設(shè)置為橢圓對(duì)應(yīng)的 cursor,即 "pointer"。
當(dāng)鼠標(biāo)移出橢圓時(shí),canvas 的 cursor 值會(huì)恢復(fù)為默認(rèn)的 "inherit"。
矩形因?yàn)闆](méi)設(shè)置為可交互,所以沒(méi)有任何反應(yīng)。
設(shè)置自定義光標(biāo)
一般來(lái)說(shuō),pixijs 只是會(huì)將 canvas 的 cursor 改為對(duì)應(yīng)的字符串值,比如 "default"。
但我們可以全局配置 app.renderer.events.cursorStyles,重新定義 "default" 為我們自定義的光標(biāo)圖片。
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';
語(yǔ)法同 CSS 的 cursor。
效果:
其實(shí)就是更新了一個(gè)映射表,當(dāng) pixijs 要設(shè)置圖形的 cursor 值時(shí),如果發(fā)現(xiàn)映射表中作為 key 有映射值,會(huì)改為使用映射值;否則直接使用圖形的 cursor 值。