JSFiddle - React, Tailwind, and code Playground
by Merlin Ye
HTML
<div>
<p>标量速度</p>
<label>vx<input value="1" id="inputVx"></label>
<label>vy<input value="0" id="inputVy"></label>
</div>
<div>
<p>矢量速度</p>
<label>v<input value="0" id="inputV"></label>
<label>rad<input value="0" id="inputRad"></label>
</div>
CSS
canvas {
margin-top: 10px;
margin-left: 10px;
border: 1px solid black;
}
JavaScript
var input = {
vx: document.getElementById('inputVx'),
vy: document.getElementById('inputVy'),
v: document.getElementById('inputV'),
rad: document.getElementById('inputRad')
}
var velocity = {
vx: 2,
vy: 2,
v: 0,
rad: 0
}
function updateVxVy(v, rad) {
input.vx.value = velocity.vx = v * Math.cos(rad)
input.vy.value = velocity.vy = v * Math.sin(rad)
}
function updateVRad (vx, vy) {
velocity.rad = Math.atan2(vy, vx)
input.rad.value = velocity.rad * 180 / Math.PI
input.v.value = velocity.v = Math.sqrt(vx * vx + vy * vy)
}
function onInputChange (e) {
var el = e.currentTarget
var name = el.name
velocity[name] = +el.value
if(el == input.vx || el == input.vy) {
updateVRad(velocity.vx, velocity.vy)
} else {
updateVxVy(velocity.v, velocity.rad * Math.PI / 180)
}
}
for(var key in input) {
input[key].name = key
input[key].addEventListener('input', onInputChange)
}
updateVRad(velocity.vx, velocity.vy)
updateVxVy(velocity.v, velocity.rad)
var Ticker = (function() {
var _callbacks = []
var _count = 0
var _tick = function () {
_callbacks.forEach(cbArr => {
var callback = cbArr[0]
var scope = cbArr[1]
callback.call(scope, _count)
})
_count++
window.requestAnimationFrame(_tick)
}
var _raf = window.requestAnimationFrame(_tick)
var instance = {}
instance.on = function (callback, scope) {
var result = _callbacks.filter(cbArr => {
return callback == cbArr[0] && scope == cbArr[1]
})
if(!result.length){
_callbacks.push([callback, scope])
}
}
instance.off = function (callback, scope) {
for (var cbArr of _callbacks) {
if(cbArr[0] == callback || cbArr[1] ==...