JSFiddle - React, Tailwind, and code Playground

by John Doe

JavaScript

/* initialize stuff */

var cvs = document.createElement('canvas')
cvs.width = 500
cvs.height = 300
var ctx = cvs.getContext('2d')

cvs.dot = function(pos, color = '#f00', r = 10) {
  ctx.fillStyle = color
  ctx.fillRect(pos[0] - r, pos[1] - r, 2 * r, 2 * r)
}

cvs.clear = function() {
  ctx.fillStyle = '#0f0'
  ctx.fillRect(0, 0, cvs.width, cvs.height)
}

document.body.appendChild(cvs)
cvs.clear()

var stickPos = [cvs.width / 2, cvs.height * 0.9]
var stickDeflect = [0, 0] //normalized to [-1,1]
var oldStickDeflect = [0, 0] //to compute derivative
var stickDeflectDt = [0, 0] //temporal derivative
var cursorPos = [cvs.width / 2, cvs.height * 0.8]
var cursorDeflect = [0, 0] //normalized to [-1, 1]

cvs.dot(stickPos)
var mouseDownPos = null
var plotLength = 40
var plotInterval = 50
var plotPoints = [
  [],
  [],
  []
]
var plotColors = ['#f00', '#a0a', '#00f']
var dt = plotInterval/1000

/* joystick function */
function stick2cursor() {
  /* given any data (e.g. stickDeflect etc)
   * write a cursorDeflect */
  p = stickDeflect[0] //stick position
  dpdt = stickDeflectDt[0]
  t = interp(Math.abs(stickDeflect[0]))
  dxdt = Math.abs(p) * 5.0 * dpdt + (1 - Math.abs(p)) * p
  cursorDeflect = [
    cursorDeflect[0] + dt * dxdt,
    0
  ]
}

function interp(p) {
  //return Math.pow(Math.sin(p * Math.PI/2), 2)
  return Math.max(Math.min(p, 1),0)
}

/* events */
cvs.onmousedown = function(e) {
  var r = cvs.getBoundingClientRect();
  mouseDownPos = [e.clientX - r.left, e.clientY - r.top]
  // cvs.clear()
  // cvs.dot(mouseDownPos)
}

cvs.onmousemove = function(e) {
  if (mouseDownPos !== null) {
    var r = cvs.getBoundingClientRect();
    var pos = [e.clientX - r.left, e.clientY - r.top]
    stickDeflect = [(pos[0] - mouseDownPos[0]) / (cvs.width / 2), (pos[1] - mouseDownPos[1]) / (cvs.width / 2)]
    // console.log(stickDeflect)
  }
}

cvs.onmouseup = function(e) {
  mouseDownPos = null
  stickDeflect = [0, 0]
}

window.setInterval(function() {
  // update derivative
 ...