JSFiddle - React, Tailwind, and code Playground

by jcubed111

HTML

<canvas id='canvas' width='500' height='500' onclick='addPoint(event);'></canvas>

CSS

body{
    background:#EEE;
    margin:0;
    padding:0;
}
canvas{
    width:500px;
    height:500px;
    background:#FFF;
}

JavaScript

//curve drawer
points = [];

function addPoint(E) {
    points[points.length] = [E.clientX, E.clientY];
    drawCurve();
}


function calcAngle(p1, p2) {
    return Math.atan2(p1[0] - p2[0], p1[1] - p2[1]);
}


function distance(p1, p2) {
    return Math.sqrt(Math.pow(p1[0] - p2[0], 2) + Math.pow(p1[1] - p2[1], 2));
}


function calcCp1(i) {
    if (i == 1) {
        return points[0];
    } else {
        a1 = calcAngle(points[i - 1], points[i - 2]);
        a2 = calcAngle(points[i - 1], points[i]);
        angle = (a1 + a2) / 2 + (Math.PI / 2);
        /*if(points[i-1][0]<=points[i-2][0]&&points[i-1][1]<=points[i-2][1]){
           angle+=Math.PI;
        }*/
        x = points[i - 1][0] + Math.sin(angle) * distance(points[i - 1], points[i]) * 0.25;
        y = points[i - 1][1] + Math.cos(angle) * distance(points[i - 1], points[i]) * 0.25;
        return [x, y];
    }
}

function calcCp2(i) {
    if (i == points.length - 1) {
        return points[i];
    } else {
        a1 = calcAngle(points[i], points[i - 1]);
        a2 = calcAngle(points[i], points[i + 1]);
        angle = (a1 + a2) / 2 - (Math.PI / 2);
        /*if(points[i][0]<=points[i-1][0]&&points[i][1]<=points[i-1][1]){
           angle+=Math.PI;
        }*/
        x = points[i][0] + Math.sin(angle) * distance(points[i - 1], points[i]) * 0.25;
        y = points[i][1] + Math.cos(angle) * distance(points[i - 1], points[i]) * 0.25;
        return [x, y];
    }
}

function drawCurve() {
    ctx = document.getElementById('canvas').getContext('2d');
    ctx.clearRect(0, 0, 500, 500);

    //draw points    
    ctx.lineWidth = 7;
    ctx.lineCap = 'round';
    ctx.strokeStyle = '#0099FF';
    for (i = 0; i < points.length; i++) {
        ctx.beginPath();
        ctx.moveTo(points[i][0], points[i][1]);
        ctx.lineTo(points[i][0], points[i][1] + .01);
        ctx.stroke();
    }

    //draw strait line    
    ctx.lineWidth = 1;
    ctx.lineCap = 'round';
    ctx.strokeStyle = '#0099FF';
   ...