JSFiddle - React, Tailwind, and code Playground

by blineberry

HTML

<canvas height="200" width="500" id="canvas"></canvas>

<p>HTML5 Canvas is supported in:</p>
<ul>
    <li>IE 9+ (1 version back)</li>
    <li>FF 2+ (16 versions back)</li>
    <li>Chrome 4+ (19 versions back)</li>
    <li>Safari 3.1+ (5 versions back)</li>
    <li>Opera 9+ (10 versions back)</li>
    <li>iOS Safari 3.2+ (4 versions back)</li>
    <li>Android Browser 2.1+ (5 versions back)</li>
    <li>Blackberry Browser 7+ (current version)</li>
    <li>Opera Mobile 10+ (4 versions back)</li>
    <li>Chrome for Android 18+ (current version)</li>
    <li>FF for Android 15+ (current version)</li>
</ul>

<p>It is unsupported in IE &lt;= 8 and Opera Mini.</p>

CSS

canvas {
    height: 200px;
    width: 500px;
    position: absolute;
    left: 50%;
    top: 50%;
    margin-left: -250px;
    margin-top: -100px;
    
    border: 1px solid silver;
    
    background: white;
}

JavaScript

function Line(positionData, color) {
    this.positionData = positionData || [];
    this.color = color || '#' + Math.floor(Math.random() * 16777215).toString(16);
    this.lineWidth = 2;
    this.lineJoin = 'round';
}

Line.prototype.getData = function() {
    var data = [];

    for (var i = 0; i < 100; i++) {
        data[i] = Math.floor(Math.random() * 201);
    }

    return this.positionData = data;
};







function Graph(canvas, args) {
    if (!canvas) {
        return false;
    }

    var options = {};

    if (args) {
        options = args;
    }

    this.canvas = canvas;
    this.height = options.height || canvas.height;
    this.width = options.width || canvas.width;
    this.xPos = this.width;
    this.pointsVisible = options.pointsVisible || 5;
    this.pointsDistance = this.width / this.pointsVisible;
    this.lines = [];

    this.context = this.canvas.getContext('2d');
};

Graph.prototype.addLine = function(line) {
    this.lines.push(line);
    return line;
};

Graph.prototype.draw = function() {
    var height = this.height;
    var width = this.width;
    var context = this.context;
    var xPos = this.xPos;
    var pointsDistance = this.pointsDistance;
    var lines = this.lines;

    for (var i = 0; i < lines.length; i++) {

        context.strokeStyle = lines[i].color;
        context.lineWidth = lines[i].lineWidth;
        context.lineJoin = lines[i].lineJoin;
        context.beginPath();
        context.moveTo(xPos - width, height - lines[i].positionData[0]);
        context.lineTo(xPos, 200 - lines[i].positionData[0]);

        for (var j = 1; j < lines[i].positionData.length; j++) {
            context.lineTo(xPos + (j * pointsDistance), 200 - lines[i].positionData[j]);
        }

        context.stroke();
    }
};

Graph.prototype.animate = function() {
    var aniCount = 0;
    var width = this.width;
    var height = this.height;
    var pointsDistance = this.pointsDistance;
    var context = this.context;
    var graph =...