pixi 介紹
Pixi是一個超快的2D渲染引擎,通過Javascript和Html技術建立動畫或管理互動式圖像,進而制作遊戲或應用。
項目位址:https://github.com/pixijs/pixi.js
API 位址:https://pixijs.download/dev/docs/index.html
中文教程位址:https://github.com/Zainking/learningPixi
遊戲中都會做一些跟整個遊戲畫面風格相符的定制光标,比如英雄聯盟中的棱形光标。在光标移動到敵對機關(互動對象)上時,會變成一把小🗡,釋放技能時又變成了另外的形狀。ps:為了找素材我特意打了一局遊戲(手動狗頭).

首先,我們需要建立一個可互動的區域。
const star = new PIXI.Graphics();
star.beginFill(0xfff8dc);
star.drawStar(200, 200, 5, 50);
star.endFill();
star.interactive = true;//啟用互動響應
star.buttonMode = true;//設定互動時光标樣式為 pointer 等同于 star.cursor = 'pointer'
app.stage.addChild(star);
在之前的文章中,我們提到過,可互動的關鍵就在于需要設定
DisplayObject
的互動屬性
interactive
。隻有當
interactive=true
時,觸摸、點選、滑鼠等事件才能被該對象捕獲到。(對于互動對象,原本的互動範圍隻是元素本身的位置範圍,但是還可以通過設定
hitArea
來定義更大的互動範圍。)
cursor : This defines what cursor mode is used when the mouse cursor is hovered over the displayObject.
buttonMode: Setting this changes the 'cursor' property to
.
'pointer'
CSS cursor 樣式
在我們看到的html中,所有的pixi繪制都是基于一個canvas實作的。也就是說,光标的變化其實都是相當于修改了canvas的
cursor
樣式。
cursor: [ [ <uri> [<x> <y>]?,]* [ auto | default | none | context-menu | help | pointer |
progress | wait |cell | crosshair | text | vertical-text | alias | copy | move |
no-drop | not-allowed | e-resize | n-resize | ne-resize | nw-resize | s-resize |
se-resize | sw-resize | w-resize | ew-resize | ns-resize | nesw-resize | nwse-resize |
col-resize | row-resize | all-scroll | zoom-in | zoom-out | grab | grabbing ] ];
1、cursor屬性适用于所有元素;
2、cursor屬性僅對具有指針裝置(如滑鼠)的裝置有效;它對觸控裝置沒有任何影響。
3、并非所有浏覽器都支援cursor屬性的所有屬性值,且所有屬性值在所有浏覽器和作業系統中顯示的效果不一定相同。
通過給不同的五角星設定不同的cursor屬性,就可以實作這樣的效果。
注意:
buttonMode
和
cursor
的值會互相覆寫,以最後設定的為準。
全局自定義cursor樣式
千呼萬喚始出來直接上代碼:
const defaultIcon = "url('imgs/bunny.png'),auto";
const hoverIcon = "url('imgs/bunny_saturated.png'),auto";
app.renderer.plugins.interaction.cursorStyles.default = defaultIcon;
app.renderer.plugins.interaction.cursorStyles.pointer = hoverIcon;
cursorStyles
(傳送門)是一個
Object<string, Object>
類型的鍵值對,string字元串是用于設定
cursor
的值,object為對應
cursor
的具體樣式内容。
這個解釋起來比較拗口,看個樣例就明白了。
const hoverIcon = "url('imgs/bunny_saturated.png'),auto";
//定義一個名為mycursor的光标樣式并綁定具體css
app.renderer.plugins.interaction.cursorStyles.mycursor = hoverIcon;
//添加一個新的互動對象并将其cursor設定為mycursor
const star = new PIXI.Graphics();
star.interactive = true;
star.cursor = 'mycursor';
...
總結
本文介紹了pixi中設定
DisplayObject
觸發互動的方式、
buttonMode
cursor
之間的關系以及
CSS cursor
,通過對全局
cursorStyles
的設定實作了全局的自定義光标。