JSFiddle - React, Tailwind, and code Playground

by Giorgio Malvone

HTML

<div id="controls">
    <input type="button" onclick="checkMode()" value="Calculate"></input>
    <label>Circle<input id="circleMode" type="radio" name="mode" checked></input></label>
    <label>Rectangle<input type="radio" id="rectMode" name="mode"></input></label>
    <label>Triangle<input type="radio"  name="mode"></input></label>
</div>
<textarea id="out"></textarea>

<canvas id="c"></canvas>

CSS

#out{
    height:150px;
    width:300px;
}

#controls,
textarea{
    display:inline-block;
}

JavaScript

var canvas = document.getElementById("c");
var ctx = canvas.getContext("2d");
canvas.width = 550;
canvas.height = 550;
ctx.fillStyle = "slateGrey";
ctx.rect(0,0,canvas.width, canvas.height);
ctx.fill();



function checkMode(){
    var circleModeButton = document.getElementById("circleMode");
    var rectModeButton = document.getElementById("rectMode");
    
    if(circleModeButton.checked){
        calcCircle();
}
    else if(rectModeButton.checked){
        calcRect();
    }
    else{
        calcTri();
    }
}
function calcCircle(){
    ctx.fillStyle = "slateGrey";
    ctx.fillRect(0,0,canvas.width, canvas.height);
    
    var radius = prompt("Enter radius:"); 
    var diameter = radius*2;
    var area = Math.PI * (radius*radius);
    var circumfrence = Math.PI * diameter;
    
    var out = document.getElementById("out");
    
    ctx.beginPath();
    ctx.arc(canvas.width/2,canvas.height/2, radius, 0, 2 * Math.PI, false);
    ctx.fillStyle = 'mediumseagreen';
    ctx.fill();
    
    out.value = "Diameter = " + diameter + "\nArea = " + area + "\nCircumfrence = " + circumfrence;

}

function calcRect(){
    ctx.fillStyle = "slateGrey";
    ctx.fillRect(0,0,canvas.width, canvas.height);

    var width = prompt("Enter width:"); 
    var height = prompt("Enter height:"); 
    var area = width*height;
    var peri = (height*2) + (width*2);
    
    var out = document.getElementById("out");
    ctx.fillStyle = "mediumseagreen";  
    ctx.fillRect(canvas.width/2,canvas.height/2,width, height);

    out.value = "Area = " + area + "\nPerimeter = " + peri;
}

function calcTri(){
    var base = prompt("Enter base:");
    var height = prompt("Enter height:");
    
    var area = (base * height)/2;
    var out = document.getElementById("out");
    out.value = "Area = " + area;
}