Custom CSS Cursor
3/28/2024
Tony Gruev
A custom cursor is a must-have for every game, it brings forward the vibe and atmosphere of the game.
We will use only CSS and JavaScript to hide the default cursor and move a custom one with an image.
It is recommended to use the OS-controller Cursor .
The CSS Typed Object Model will be utilized for a better performance.
A sample showing changing the mouse cursor image and increasing its size can be found in the Gameface package in folder Samples\uiresources\UITutorials\CustomCSSCursor.
Fist of all we hide the default cursor with:
Now the element for that cursor is:
The styles for the cursor:
Although the default cursor may not be visible, it remains present. Therefore, when we click on the document, the .cursor
element will capture the pointer events. To prevent this and allow the event to propagate to the element beneath the .cursor
element, we must disable its pointer-events using pointer-events: none
.
Important: Make sure the .cursor
element has the highest z-index
value over all the elements on the page. In case you don’t change the z-index
- placing the .cursor
element at the end of the <body>
without z-index
will suffice.
Mouse Movement Using attributeStyleMap
And finally the JavaScript we need:
The cursor icon can be changed easily also.
For example, by entering another element:
And this requires only for the background image to be changed:
Limitations and Peculiarities
There are some particularities that need to be taken into account.
Remove the body margin
Disabling the margin
on the body prevents the cursor element from being offset from the OS cursor position.
Scrollable Page
In case the page is scrollable, you will need to take that into account in the mousemove
EventListener:
Also the cursor element is updated only on mousemove
and there is a need to watch for scrolling with the scroll
event:
and the coordinates can be saved in the mousemove
EventListener :
Frame rate dependency
Since this front-end approach is relying on how fast the application is running, there will be a delay after moving the mouse and when the cursor element catches on. The lower the frame rate, the bigger the delay.
For information how to use the OS-controlled cursor, check the section below.
OS-controller Cursor (Recommended)
It is recommended to use the OS-controlled cursor - read the Cursor control in the Gameface documentation.