JSFiddle - React, Tailwind, and code Playground

by andrelaszlo

HTML

<canvas id="c" width="500" height="500"></canvas>
<br>
<input id="value" type="range" value="200" min="1" max="120000"><input type="text" id="range-val">

CSS

body, html {
    margin: 0; padding: 0;
}

#c {
    border: 1px solid black;
}

#value {
    width: 450px;
}

#range-val {
    width: 50px;
    border: 0px;
    text-align: right;
}

JavaScript

function ValueHistory(interval) {
	var history = [];

	var clean = function(now, value) {
		console.log('history', history.length);
		now = now || +new Date();
		value = value || -Infinity;
		var history_filtered = history.filter(function(item){
			var bigger = item.value > value;
			var diff = now - item.ts;
			return bigger && (diff <= interval) ;
		});
		if (history_filtered.length) {
			history = history_filtered;
		}
	};

	var update = function(value) {
		var now = +new Date();
		value = +value;
		clean(now, value);
		history.push({
			ts: now,
			value: value
		});
	};

	var max = function() {
		if (!history)
			return 0;
		return history
			.map(function(x){ return x.value; })
			.reduce(function(x0, x1) {
				return Math.max(x0, x1);
			}, 0);
	};

	return {
		update: update,
		clean: clean,
		max: max
	};
}

$(function() {
    var canvas = document.getElementById('c');
    var context = canvas.getContext('2d');
    var centerX = canvas.width / 2;
    var centerY = canvas.height / 2;

	var max_size = Math.min(centerX, centerY)-5;
    var $val = $("#value");
    var $val_disp = $("#range-val");
    var history = new ValueHistory(5000);
	var history2 = new ValueHistory(10000);
    
    function humanize(val) {
        if ( val > 1000) {
            return "" + Math.round(val/1000) + "s";
        }
        return "" + val + "ms";
    }
    
    function value2radius(val) {
        // A = pi*r^2, 2*v = A
        // => r = sqrt(2*v/pi)
		var radius = Math.sqrt(2*val/Math.PI);
        return Math.max(3, Math.min(max_size, radius));
    }
    
    function circle(radius, color, stroke) {
        context.beginPath();
        context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
        context.fillStyle = color;
        context.fill();
        if (stroke) {
            context.lineWidth = 1;
            context.strokeStyle = '#333';
            context.stroke();
        }
    }
    
    function redraw() {
		var radius = value2radius($val.val());
       ...