A simple joystick component for web app using pure TypeScript. It can be used as control element.
You can create Joystick simply by implementing joystick.min.js file and run code below
new Joystick();
However, to run it without any arguments you have to create HTML element with 'joystick' id before.
Joystick class normally gets two arguments
new Joystick([HTMLElement], [options]);
Where:
- HTMLElement is DOM element grabbed by javascript code using f.e. querySelector method.
- options is object containing three properties:
const options = {
scale: 1,
color: "#000000",
strokeColor: "#ffffff"
};
scale - Joystick is scalable, by default width and height are 100px,
color - main color of joystick,
strokeColor - stroke color of inner joystick element.
joy.directionVector();
Returns joystick's displacement vector object with x and y properties {x: ..., y: ...}
. Values range from 0 to 1.
joy.displacementValue();
Returns value from 0 to 1 based on how joystick's position is far from it's center.
joy.directionAngleRads();
Returns joystick's direction angle in radians.
joy.directionAngleDegs();
Same in degrees.
joy.direction();
Returns string containing cardinal direction based on an angle from an array ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"]
.
Joystick contains three events to work on.
Change - event dispatched when Joystick element is in move.
const joy = new Joystick();
joy.on("change", (joystickObject) => { /* code here */ });
Start - event dispatched when Joystick starts moving.
const joy = new Joystick();
joy.on("start", (joystickObject) => { /* code here */ });
End - event dispatched when Joystick ends moving.
const joy = new Joystick();
joy.on("end", (joystickObject) => { /* code here */ });
First of all implement Joystick library
<script src="joystick.min.js"></script>
Then create HTML element
<div id="iWantItHere"></div>
And then final step will be
new Joystick(
document.querySelector("#iWantItHere"),
{
scale: 2,
color: "rgb(255, 0, 255)",
strokeColor: "rgb(0, 0, 0)"
}
)
We are set!
Live example is availible at link.