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的设置实现了全局的自定义光标。

posted @ 2021-01-11 10:41  傅小灰  阅读(1166)  评论(0编辑  收藏  举报