JSFiddle - React, Tailwind, and code Playground
by benjaminjenett
HTML
<canvas id="canvas" width=200 height=200></canvas>
<div class="controls">
<div>
<label>Amplitude (<span id="a_slider_label">0</span>)</label>
<input id="a_slider" type="range" min=0 max=20 value=0 step=0.1></input>
</div>
<div>
<label>Frequency (<span id="f_slider_label">0</span>) Hz</label>
<input id="f_slider" type="range" min=0 max=5 value=0 step=0.1></input>
</div>
</div>
CSS
body {
font-family: Helvetica, Arial, sans-serif;
font-size: 12px;
}
canvas {
display: block;
margin: 20px auto;
width: 200px;
height: 200px;
border: 1px solid #333;
}
.controls {
width: 400px;
margin: 10px auto;
}
.controls > div {
border-bottom: 1px solid #EEE;
padding: 5px 0;
}
.controls label {
width: 200px;
display: inline-block;
}
.controls input {
vertical-align: middle;
}
JavaScript
/* Spring stiffness, in kg / s^2 */
/*var k = -20;*/
var spring_length = 180;
/* Damping constant, in kg / s */
/*var b = -0.5;*/
/* Block position and velocity. */
/*var block = {x: 100, v: 0, mass: 0.5};*/
var wall = {x: 20, lx: 30, v: 0, t: 0, frequency: 0, a: 0};
var frameRate = 1/30;
var frameDelay = frameRate * 1000;
var canvas;
var ctx;
var width = 200;
var height = 200;
var loop = function() {
/* Move the wall. */
wall.t += frameRate;
wall.lx = wall.x;
wall.x = wall.a * Math.sin(2 * Math.PI * wall.frequency * wall.t);
wall.v = (wall.x - wall.lx) / frameRate;
/* Drawing */
ctx.clearRect(0, 0, width, height);
ctx.save();
ctx.fillStyle = '#CCCCCC';
ctx.fillRect((width/2)-20, height/2 - (wall.x-5), 40, 10);
ctx.restore();
};
var setup = function() {
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
document.getElementById('a_slider').onchange = function() {
this.innerHTML = this.value;
wall.a = 1 * parseFloat(this.value);
document.getElementById('a_slider_label').innerHTML = wall.a;
};
document.getElementById('f_slider').onchange = function() {
this.innerHTML = this.value;
wall.frequency = parseFloat(this.value);
document.getElementById('f_slider_label').innerHTML = wall.frequency;
};
setInterval(loop, frameDelay);
};
setup();