-
Notifications
You must be signed in to change notification settings - Fork 0
/
joystick.min.js
7 lines (6 loc) · 1.37 KB
/
joystick.min.js
1
2
3
4
5
6
7
/*!
* JoyStick v0.2.1 (https://github.com/RodnyE/JoyStick)
* Copyright 2022 Rodny Estrada
* Licensed under the MIT license
*/
JoyStick=function(t,e={}){let s=this,a=document.createElement("canvas"),n=e.eventArea||a,i=a.getContext("2d"),o=e.fillStyle||"#000000",l=e.strokeStyle||e.fillStyle||"#000000",$=e.callback,c=t.clientWidth,f=t.clientHeight,h=c/2,r=f/2,d=h;a.width=c,a.height=f,t.appendChild(a);let p=h,y=r,b=d/2,g=d-b,u="BODY"===a.offsetParent.tagName.toUpperCase()?a:a.offsetParent,x=u.offsetLeft,P=u.offsetTop;function v(){i.clearRect(0,0,c,f),i.fillStyle=o,i.strokeStyle=l,i.beginPath(),i.arc(h,r,3*d/4,0,2*Math.PI,!1),i.lineWidth=2,i.stroke(),i.closePath(),i.beginPath(),i.arc(p,y,b,0,2*Math.PI,!1),i.fill(),i.closePath()}n.addEventListener("touchstart",function(){s.pressed=!0,$&&$(s.x,s.y)}),n.addEventListener("touchmove",function(t){let e=(t=t.targetTouches[0]).pageX-x,a=t.pageY-P,n=e-d,i=a-d,o=Math.atan2(i,n);n*n+i*i>=g*g?(p=g*Math.cos(o),y=g*Math.sin(o)):(p=Math.abs(n)>g?g:Math.abs(n),y=Math.abs(i)>g?g:Math.abs(i)),i<0&&(y=-Math.abs(y)),n<0&&(p=-Math.abs(p));let l=((p+=d)-h)/g,c=((y+=d)-r)/g,f=Math.sqrt(l*l+c*c);s.x=l,s.y=c,s.s=f>.9999999?1:f,x=u.offsetLeft,P=u.offsetTop,v(),$&&$(s.x,s.y)}),n.addEventListener("touchend",function(){s.pressed=!1,p=h,y=r,s.x=0,s.y=0,s.s=0,v(),$&&$(s.x,s.y)}),this.container=t,this.canvas=a,this.context=i,this.x=0,this.y=0,this.pressed=!1,v()};