JSFiddle - React, Tailwind, and code Playground
by chadarsenault
HTML
<button id="stop">Stop</button>
<button id="go">Go</button>
<button id="clear">Clear</button>
<canvas id="container" class="container"></canvas>
CSS
*{box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;}
.container {
display: block;
margin-top: 2em;
border: 1px solid #666;
height: 300px;
width: 100%;
}
JavaScript
var canvas = document.getElementById('container');
var canvasH = canvas.height;
var canvasW = canvas.width;
if(canvas.getContext) {
var context = canvas.getContext('2d');
}
var disp = 0;
var yPoint = canvasH;
var interval = canvasW / 10;
function reset() {
disp = 0;
yPoint = canvasH;
interval = canvasW / 10;
}
$('#stop').on('click', function() {
reset();
if(typeof counter!== 'undefined') {
clearInterval(counter);
}
});
$('#go').on('click', function() {
reset();
counter = setInterval(function() {
var randNum = Math.round(Math.random() * (canvasH - 0) + 0);
context.beginPath();
context.moveTo(disp,yPoint);
context.lineTo(disp += interval,randNum);
context.stroke();
yPoint = randNum;
}, 500);
});
$('#clear').on('click', function() {
reset();
context.clearRect(0, 0, canvas.width, canvas.height);
});