pixi.js 自定義光標樣式


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屬性,就可以實現這樣的效果。

cursor

注意:buttonModecursor的值會互相覆蓋,以最后設置的為准。

全局自定義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觸發交互的方式、buttonModecursor之間的關系以及CSS cursor,通過對全局cursorStyles的設置實現了全局的自定義光標。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM