Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using it's URL and the proper URL extention.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                
<html>

<head>

<style>

* {	margin: 0;
	padding: 0;
}

.cntnr {
	text-align:center;
	}

.nmbr{
	/*border:1px solid black;*/
	margin-right:-2px;
	margin-left:-2px;
	margin-top:-10px;
	padding:0;
}

.opsDot{
	/*border:1px solid red;*/	
}

.topCnvs{	
	position:absolute;
	left:0;
	top:0;
	z-index:1;
}

.dotPad{
	padding-bottom: 3px;
}

.topDiv{
	height: 1000px;
	position:absolute;
	left:100px;
	top:0;
	z-index:2;
	text-align:center;
	}

</style>

</head>

<!--
There are two canvases - a top canvas(see .topDiv class, z-index=2), which holds all the actual calculator
items (and positioning is excruciating), and a bottom canvas (z-index=1) which holds the reddish outline.

It's a lot easier for me to understand and work on this application if it is
monolithic - the CSS and javascript and HTML all in this one file, so that's the way
I am leaving it. 
-->

<body style="background-color: rgb(235, 225,0)" >

<canvas id="topCanvas" width="800px" height="1000px" style="position:absolute;left:0top:0;z-index:1">
</canvas>

<div class="topDiv">

<div style="height:28px" ></div>
<div style="height: 12px;" class="cntnr" id="showNmbr"></div>
<div style="height:20px" ></div>



<div class="cntnr">
	<canvas class = "nmbr" width="40px" height="40px" data-number="1"></canvas>
</div>
<div class="cntnr">
	<canvas class = "nmbr" width="40px" height="40px"  data-number="2"></canvas>
	<canvas class = "nmbr" width="40px" height="40px"  data-number="3" ></canvas>
</div>
<div class="cntnr">
	<canvas class = "nmbr" width="40px" height="40px" data-number="4"></canvas>
</div>


<div class="cntnr">
	<canvas class = "nmbr" width="40px" height="40px"  data-number="5"></canvas>
	<canvas class = "nmbr" width="40px" height="40px"  data-number="6" ></canvas>
</div>
<div class="cntnr">
	<canvas class = "nmbr" width="40px" height="40px" data-number="7"></canvas>
</div>
<div class="cntnr">
	<canvas class = "nmbr" width="40px" height="40px"  data-number="8"></canvas>
	<canvas class = "nmbr" width="40px" height="40px"  data-number="9" ></canvas>
</div>
<div class="cntnr">
	<canvas class = "nmbr" width="40px" height="40px" data-number="0"></canvas>
</div>

<div style="height:5px" ></div>
<div class="cntnr">
	<canvas class="opsDot" width="30px" height="30px"  data-ops="*">&nbsp;</canvas>
	<canvas class="opsDot" width="30px" height="30px"  data-ops="/">&nbsp;</canvas>
	<canvas class="opsDot" width="30px" height="30px"  data-ops=".">&nbsp;</canvas>
	<canvas class="opsDot" width="30px" height="30px"  data-ops="+">&nbsp;</canvas>
	<canvas class="opsDot" width="30px" height="30px"  data-ops="-">&nbsp;</canvas>
</div>
<div class="cntnr">
	<canvas class="opsDot" width="88px" height="30px"  data-ops="reset">&nbsp;</canvas>
	<canvas class="opsDot" width="88px" height="30px"  data-ops="=">&nbsp;</canvas>
</div>

</div>

<script>

/*
The functionality is implemented as a state machine. 
The state machine does the calculation.
There are two sets of javascript functions - one for
display, the other for the state machine.
These are largely but not completely separate. Some state-machine functions have
one-line calls to display something. Since each mouse click (apart from errors) requires
a change in the display, it was simplest to implement it this way.

Some eccentricities: Number cannot begin with zero. It cannot end with a decimal point.
Unary + is not displayed. Numbers have a maximum number of digits, and a max and min size.
*/

window.resizeTo(400,480);

var outpt = false; 	// if true, write stuff to console. If false, silence.

/* The global variables below are used for the state machine.
Not too elegant, but sufficient for such a small application.
*/

var state = "begin";		// states are strings - begin, start, fract, 
				// negate, numeric, newop and badnumber.
				// see state-machine section.
		
var nmbrObjs = {};		// info about each circle (circles have numbers) 
				// see constructor numberObject()
var opsObjs = {};		// info about reset, +, *, etc	
				// see constructor opsObject	
var currentNumber = undefined;  // 'current' number being entered, as string
var calculatedValue=undefined;// running value being calculated
var currentOp = undefined;	// string, the current operator, reset, etc
var hasDot = false; 		// true if number has decimal point
var negateNumber = false;	// true if there was unary minus
var maxNumDigits = 8;		// max number of digits or decimal places in number
var numDigits = 0;		// keeps track of the number of digits
var maxNumber = 999999999999; // the largest possible number for this calculator.
var minNumber = .0000000001;	// the smallest number. It means zero is not allowed,
				// which is fine for simple arithmetic (who needs zero?).

var div = String.fromCharCode(0x00F7); //division symbol
var times = String.fromCharCode(215);   // multiplication symbol
var useSymbols = { "*":times,"/":div};

/* ************************************************************

				USER INTERFACE SECTION

************************************************************** */

setup();
if(outpt)console.log(nmbrObjs);

function setup(){
	setupNmbrObjects();
	setupCircleColors();
	for(var key in nmbrObjs){
		drawCircle(nmbrObjs[key]);
	}
	setupOpsObjects();
	setupSquareColors();
	for(var key in opsObjs)
		fillSquare(opsObjs[key]);

	//tempDrawLine();
	drawOutline();
}



function drawOutline(){
	var c=document.getElementById("topCanvas");
	var ctx=c.getContext("2d");
	ctx.beginPath();
	ctx.lineWidth=8;
	ctx.strokeStyle="rgb(150,0,0)";

	// bottom left start arc up
	var startx = 150;
	var starty = 288;
	var startx0 = startx;
	var starty0 = starty;
	var endx = 90;
	var endy = 120;
	var cp1y = starty - 50;
	var cp2y = endy + 50;
	ctx.moveTo(startx,starty);
	ctx.bezierCurveTo(startx, cp1y,endx, cp2y, endx, endy);
	ctx.stroke();

	// continue arc to top
	var startx1 = endx;
	var starty1 = endy;
	var delx = 100;
	var dely = 75;
	var endx1 = startx1 + delx;
	var endy1 = 15;
	var ctpt1y = starty1-50;
	var ctpt1x = endx1 - 50;
	ctx.moveTo(startx1, starty1);
	ctx.bezierCurveTo(startx1, ctpt1y, ctpt1x, endy1, endx1, endy1);
	ctx.stroke();

	//bottom right start arc
	var cntr = endx + delx;
	startx = startx + 2*(cntr - startx);
	endx += 2*(cntr - endx);
	ctx.moveTo(startx,starty);
	ctx.bezierCurveTo(startx, cp1y,endx, cp2y, endx, endy);
	ctx.stroke();
	var x1 = startx;
	var y1 = starty;

	ctx. moveTo(endx, endy);
	ctx.bezierCurveTo(endx, ctpt1y, endx1+50, endy1, endx1, endy1);
	ctx.stroke();

	startx = startx0;
	starty = starty0;
	corry = 4;
	ctx.moveTo(startx,starty - corry); //
	var ddx = 80;
	ddy = 95;
	ctx.lineTo(startx-ddx,starty - corry); // H to left
	//ctx.stroke();
	ctx.lineTo(startx-ddx, starty+ddy); // V down
	ctx.lineTo(startx + 2*ddx, starty+ddy ); // H to right
	ctx.lineTo(startx + 2*ddx, starty - corry); // Vup
	ctx.lineTo(x1,y1 - corry); //H to left
	ctx.stroke();
}



// constructor
function numberObject(elem, num, circleColor, textColor, flashColor){
	this.element = elem;
	this.number = num; // string
	this.width = elem.width;
	this.height = elem.height;
	this.circleColor = circleColor;
	this.textColor = textColor;
	this.flashColor= flashColor;
	this.context = elem.getContext("2d");	
}

// one day I'll figure out inheritance in javascript
// constructor
function opsObject(elem, symbol, squareColor, textColor, flashColor){
	this.element = elem;
	this.symbol = symbol; // string
	this.width = elem.width;
	this.height = elem.height;
	this.squareColor = squareColor;
	this.textColor = textColor;
	this.flashColor= flashColor;
	this.context = elem.getContext("2d");	
}

function setupCircleColors(){
	var num = 0;
	var str;
	var start =220;
	var stop = 255;
	var step = (stop - start)/7;
	var blue = 215;
	bstep = 5
	for(var green = start; green <= stop; green += step){
		blue += bstep;
		str="rgb(100," + Math.floor(green).toString() + ", " + blue.toString() + ")";
		if(outpt)console.log(str);
		num++;
		if (num === 1){
			nmbrObjs["1"].circleColor = str;
		} else if (num === 2){
			nmbrObjs["2"].circleColor = str;
			nmbrObjs["3"].circleColor = str;
		} else if (num == 3){
			nmbrObjs["4"].circleColor = str;
		} else if (num == 4){
			nmbrObjs["5"].circleColor = str;
			nmbrObjs["6"].circleColor = str;
			
		} else if (num == 5){
			nmbrObjs["7"].circleColor = str;
		} else if (num == 6){
			nmbrObjs["8"].circleColor = str;
			nmbrObjs["9"].circleColor = str;
		} else if (num == 7){
			nmbrObjs["0"].circleColor = str;
		}
	}
}

function setupSquareColors(){
	var color = "hsl(175 , 100% , 85%)";
	for(var key in opsObjs){
		opsObjs[key].squareColor = color;
	}
}



function setupNmbrObjects(){
	var nmbrArray = document.getElementsByClassName("nmbr");
	for(var i=0;i<nmbrArray.length;i++){
		var elem =nmbrArray[i];
		var num= elem.dataset.number;
		var obj = new numberObject(elem, num, "white", "black", "green");
		if(outpt)console.log(obj);
		nmbrObjs[num] = obj;
		elem.addEventListener("click", circleClicked, false);
	}
}

function setupOpsObjects(){
	if(outpt)console.log("setupOpsObjects");
	var opsArray = document.getElementsByClassName("opsDot");
	for(var i=0;i<opsArray.length;i++){
		var elem =opsArray[i];
		var symbol= elem.dataset.ops;
		var obj = new opsObject(elem, symbol, "white", "black", "red");
		if(outpt)console.log(obj);
		opsObjs[symbol] = obj;
		elem.addEventListener("click", squareClicked, false);

		
	}
}

function drawCircle(nmbrObj ){
	
		ctx = nmbrObj.context;
		if(! ctx)
			if(outpt)console.log("NO CANVAS");
		else
			if(outpt)console.log(ctx);
		
		wd = nmbrObj.width;
		ht = nmbrObj.height;
		
		ctx.beginPath();
		ctx.arc(wd/2., ht/2., wd/2., 0, 2*Math.PI);
		ctx.fillStyle = nmbrObj.circleColor;
		ctx.fill();

		ctx.fillStyle= nmbrObj.textColor;
		ctx.font = "20px serif";
		var num = nmbrObj.number;
		var fracw=.68;
		var frach = 1.3;
  		ctx.fillText(num, fracw*wd/2., frach*ht/2.);
}

function fillSquare(opsObj){
	var ctx = opsObj.context;
	wd = opsObj.width;
	ht = opsObj.height;
	ctx.fillStyle = opsObj.squareColor;
	ctx.fillRect(0,0,wd,ht);

	ctx.fillStyle=opsObj.textColor;
	ctx.font = "20px serif";
	var sym = opsObj.symbol;
	if(sym in useSymbols) sym = useSymbols[sym];
	// centering by eyeball - hack hack
	var fracw=.68;
	var frach = 1.3;
	if(sym === "."){
		frach=1.0;
		fracw = .77;
	}
	if(sym == "=") fracw = .85;
	if(sym == "-")fracw = .8;
  	ctx.fillText(sym, fracw*wd/2., frach*ht/2.);
}

function circleClicked(e){
	if(outpt)console.log("CLICKED");
	if(outpt)console.log(this);
	if(outpt)console.log(e);

	var num = this.dataset.number;

	/* Because of overlap in boxes, if the click is in the 
	bottom/side of one circle which is near the top/side of a different circle
	(or vice versa), then we have to compensate - and find the correct place. 
	Hack! Hack! Hack!*/

	var obj;
	if( (num == 2)|| (num == 3)){
		obj = nmbrObjs["1"];
		if(isClickInCircle(e, obj)) num="1";
	} else if(num == 4){
		obj = nmbrObjs["2"]
		if(isClickInCircle(e, obj)){
			num="2";
		}else{
			obj=nmbrObjs["3"];
			if(isClickInCircle(e,obj))num="3";
		}
	} else if ((num == 5)||(num == 6)){
		obj=nmbrObjs["4"];
		if(isClickInCircle(e,obj))num = "4";
	}else if(num == 7){
		obj = nmbrObjs["5"]
		if(isClickInCircle(e, obj)){
			num="5";
		}else{
			obj=nmbrObjs["6"];
			if(isClickInCircle(e,obj))num="6";
		}
	}else if ((num == 8)||(num == 9)){
		obj=nmbrObjs["7"];
		if(isClickInCircle(e,obj))num = "7";
	}else if(num == 0){
		obj = nmbrObjs["8"]
		if(isClickInCircle(e, obj)){
			num="8";
		}else{
			obj=nmbrObjs["9"];
			if(isClickInCircle(e,obj))num="9";
		}
	}	
	
	var obj = nmbrObjs[num];
	if(! isClickInCircle(e, obj)) return;
	flashNumber(obj);
	handleDigit(num);
}

function squareClicked(e){
	if(outpt)console.log("SQUARE CLICKED");
	var symbol = this.dataset.ops;
	var obj = opsObjs[symbol];
	flashSquare(obj);
	handleOp(symbol);
}

function isClickInCircle(e, nmbrObj){
	var elem = nmbrObj.element;
	var rect = elem.getBoundingClientRect();
	//console.log(rect.top, rect.right, rect.bottom, rect.left);
	var top = rect.top;
	var left = rect.left;
	var rad = nmbrObj.width/2.; // assume width=height
	var ycntr = top + rad;
	var xcntr = left + rad;
	//console.log(xcntr + "  " + ycntr);
	var mx = e.clientX;
	var my = e.clientY;
	//console.log("mx,my: " + mx + "  " + my);
	var dis = Math.sqrt( Math.pow((xcntr-mx),2) + Math.pow((ycntr-my),2) );
	//console.log("dis: " + dis);
	return (dis < rad);
}

function flashNumber(nmbrObj){
	if(outpt)console.log("FLASH");
	var ctx = nmbrObj.context;
	var clr = nmbrObj.flashColor;
	var wd = nmbrObj.width;
	var ht = nmbrObj.height;
	ctx.beginPath();
	ctx.arc(wd/2., ht/2., wd/2., 0, 2*Math.PI);
	ctx.fillStyle = clr;
	ctx.fill();
	setTimeout(function(){
		drawCircle(nmbrObj);
		}, 75);
}

function flashSquare(opsObj){
	var ctx = opsObj.context;
	var clr = opsObj.flashColor;
	var wd = opsObj.width;
	var ht = opsObj.height;
	ctx.fillStyle = clr;
	ctx.fillRect(0,0,wd,ht);

	setTimeout(function(){
		fillSquare(opsObj);
		}, 75);

}


function display(){
	var elmn = document.getElementById("showNmbr");
	elmn.innerHTML=currentNumber;
}

function displayCalculatedValue(){
	if(calculatedValue===undefined)return;
	var elmn = document.getElementById("showNmbr");
	elmn.innerHTML=calculatedValue.toString();
}

function displaySymbol(symbol){
	var elmn = document.getElementById("showNmbr");
	if(symbol in useSymbols) symbol = useSymbols[symbol];
	elmn.innerHTML = symbol;
}

function clearDisplay(){
	var elmn = document.getElementById("showNmbr");
	elmn.innerHTML = " ";
}

function displayBadNumber(){
	var elmn = document.getElementById("showNmbr");
	elmn.innerHTML = "**********";
}




/* ************************************************************

				STATE-MACHINE SECTION

************************************************************** */

// I prefer "if" statements to case.

// received digit from UI
function handleDigit(num){
	if(outpt)console.log("handleDigit");
	if(state == "begin"){
		state = "start";
		return startDigit(num);
	}
	if(state == "start") return startDigit(num);
	if(state == "fract") return fractDigit(num);
	if(state == "negate") return negateDigit(num);
	if(state == "numeric")return numericDigit(num);
	if(state == "newop")  return newopDigit(num);
	if(state == "badnumber") return badnumberDigit(num);
}

// receive operator (squares) from UI
function handleOp(symbol){
	if(outpt)console.log("handleOp");
	if(symbol == "reset") return reset();

	if(state == "begin"){
		state = "start";
		return startOp(symbol);
	}
	if(state == "start") return startOp(symbol);
	if(state == "fract") return fractOp(symbol);
	if(state == "negate") return negateOp(symbol);
	if(state == "numeric")return numericOp(symbol);
	if(state == "newop")  return newopOp(symbol); 
	if(state == "badnumber") return badnumberOp(symbol);
}

// state = "start" a digit has arrived
// first digit cannot be 0 if no leading decimal point
function startDigit(num){
	if(outpt)console.log("startDigit");
	if(num == 0) return;
	state = "numeric";
	numericDigit(num);
}

// state == "fract" and a digit has arrived
// the digit will have arrived after a decimal point has been added
function fractDigit(num){
	if(outpt)console.log("fractDigit");
	state = "numeric";
	return numericDigit(num);
}

// state == "negate" and a digit has arrived
// the digit will have arrived after the minus sign has been added
// but before any digits have been added, so 0 is not allowed
// there won't be leading decimal point in this state
function negateDigit(num){
	if(outpt)console.log("negateDigit");
	if(num == 0) return;
	state = "numeric"
	return numericDigit(num);
}

//state = "numeric" and a digit has arrived
function numericDigit(num){
	if(outpt)console.log("numericDigit");
	if(currentNumber === undefined)currentNumber = "";
	if(numDigits >= maxNumDigits) return;
	currentNumber += num.toString();
	numDigits++;
	display();
}

// state = "newop" and a digit has arrived.
// expecting an operator - so nothing should happen
function newopDigit(num){
	if(outpt)console.log("newopDigit");
}

// state = "badnumber" and digit has arrived
function badnumberDigit(num){
	if(outpt)console.log("badnumberDigit");
	reset();
	state = "start";
	startDigit(num);
}

//state = "start" and a symbol has arrived	
function startOp(symbol){
	if(outpt)console.log("startOp");
	if(symbol == "-"){
		state = "negate";
		return negateOp(symbol);
	}
	if(symbol == "."){
		state = "fract";
		return fractOp(symbol);
	}
}

// state = "negate", add - sign to currentNumber if symbol = "-"
function negateOp(symbol){
	if(outpt)console.log("negateOp");
	if(symbol == "."){
		state = "fract";
		return fractOp(symbol);
	}

	if(negateNumber) return; // - sign already added
	if(symbol != "-") return;
	if(currentNumber === undefined) currentNumber = "";
	currentNumber += "-";
	negateNumber = true;
	display();
}

// state = "fract" - add decimal point to number
// might be a - sign already there, or we could be in the middle of the number
function fractOp(symbol){
	if(outpt)console.log("fractOp");
	if(symbol != ".") return;
	if(hasDot) return;
	hasDot = true;
	if(currentNumber === undefined) currentNumber = "";
	currentNumber += ".";
	display();
}

/* state is "numeric" (building the number) and an
operator has arrived. This triggers a calculation.
reset handled elsewhere.
*/
function numericOp(symbol){
	if(outpt)console.log("numericOp");
	// check for decimal in middle of number
	if((symbol == ".")&&(! hasDot)){
		state = "fract";
		fractOp(symbol);
		return;
	}
	if( (symbol == ".")&& hasDot) return;
	calculate(); // May set state to badnumber. 
	resetNumber();
	currentOp = undefined;
	if(state == "badnumber"){
		displayBadNumber();
		return;
	} 
	state = "newop";
	return newopOp(symbol);
}

// state is newop and a symbol has arrived
function newopOp(symbol){
	if(outpt)console.log("newopOp");
	if(symbol == ".") return;
	if((currentOp === undefined)&&(symbol == "=")){
		if(outpt)console.log("newopOp**A: " + calculatedValue);
		// must get an operator to act on calculatedValue
		// do not change state
		displayCalculatedValue();
		return;
	}
	if(currentOp === undefined){
		if(outpt)console.log("newopOp**B: " + calculatedValue);
		currentOp = symbol;
		state = "start";
		displaySymbol(symbol);
	}else {
		//ERROR
	}
}

function badnumberOp(symbol){
	if(outpt)console.log("badnumberOp");
	reset();
	if(symbol == "-"){
		state = "start";
		return startOp(symbol);
	}
	state="begin";
}

function reset(){
	currentNumber=undefined;
	calculatedValue=undefined;
	currentOp = undefined;
	hasDot = false;
	negateNumber = false;
	state="begin";
	numDigits = 0;
	clearDisplay();
}

function resetNumber(){
	currentNumber="";
	hasDot = false;
	negateNumber = false;
	clearDisplay();
	numDigits=0;
}



function calculate(){
	if(outpt)console.log("calculate: " + calculatedValue);
	if(outpt)console.log("calculate: currentOp: " + currentOp);
	if(outpt)console.log("calculate: currentNumber: " + currentNumber);

	var num = Number(currentNumber);
	if(outpt)console.log("calculate: num: " + num);
	if(calculatedValue === undefined){
		calculatedValue = num;
		return;
	}

	if(currentOp == "+")
		calculatedValue += num;
	else if (currentOp == "-")
		calculatedValue -= num;
	else if (currentOp == "*")
		calculatedValue *= num;
	else if (currentOp == "/")
		calculatedValue /= num;


	var x = calculatedValue;
	if(x < 0) x = -x;
	if((x > maxNumber)||(x < minNumber)){
		state="badnumber";
		return;	
	}
	var str = calculatedValue.toString();
	var len = str.length;
	if(len > 12){
		str = str.substring(0,11);
	}
	calculatedValue = Number(str);


}







</script>

</body>

</html>
              
            
!

CSS

              
                
              
            
!

JS

              
                
              
            
!
999px

Console