cssAudio - Activefile-genericCSS - ActiveGeneric - ActiveHTML - ActiveImage - ActiveJS - ActiveSVG - ActiveText - Activefile-genericVideo - ActiveLovehtmlicon-new-collectionicon-personicon-teamlog-outoctocatpop-outspinnerstartv

Pen Settings

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. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

Looking for quick-add? Try the external resource search, it's quicker and gives you access to the most recent version of thousands of libraries. ☝️

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

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

Looking for quick-add? Try the external resource search, it's quicker and gives you access to the most recent version of thousands of libraries. ☝️

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

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.

            
              <div class="wrapper">
  <header>
  <h1>Jackie's <span class="can-speak">*</span> Calculator</h1>
  <p><span class="can-speak">*</span> A calculator that speaks in Chrome and Safari</p>
</header>
<main>
  <canvas width="300" height="500" id="calculator"></canvas>

</main>
<footer>
  &copy; 2015 Se&aacute;n Behan
</footer>
</div>
            
          
!
            
              body {
  background: #fafafa;
  color: #000000;
  font-size: 16px;
}

.can-speak {
  color: #E1163C;
}

h1 {
  font-family: "Share Tech Mono", sans-serif;
  font-size: 2em;
  margin: 10px;
}

.pointer {
  cursor: pointer;
}

.wrapper {
  min-width: 300px;
  text-align: center;
}
            
          
!
            
              var calcCanvas = document.getElementById("calculator"),
    canvasLeft = calcCanvas.offsetLeft,
    canvasTop = calcCanvas.offsetTop,
    ctx = calcCanvas.getContext('2d'),
    buttons = [
      {x: 60, y: 220, char: '7', op: false},
      {x: 120, y: 220, char: '8', op: false},
      {x: 180, y: 220, char: '9', op: false},
      {x: 240, y: 220, char: '\u00F7', op: true}, // division
      {x: 60, y: 280, char: '4', op: false},
      {x: 120, y: 280, char: '5', op: false},
      {x: 180, y: 280, char: '6', op: false},
      {x: 240, y: 280, char: '\u00D7', op: true}, // multiplication
      {x: 60, y: 340, char: '1', op: false},
      {x: 120, y: 340, char: '2', op: false},
      {x: 180, y: 340, char: '3', op: false},
      {x: 240, y: 340, char: '\u2212', op: true}, // minus
      {x: 60, y: 400, char: '0', op: false},
      {x: 120, y: 400, char: '\u002E', op: false}, // decimal point
      {x: 180, y: 400, char: '\u003D', op: true}, // equals
      {x: 240, y: 400, char: '\u002B', op: true} // addition
    ],
    runningTotal = 0,
    displayArr = [],
    operators = {
      '\u002B': function(a, b) {return a + b;},
      '\u2212': function(a, b) {return a - b;},
      '\u00D7': function(a, b) {return a * b;},
      '\u00F7': function(a, b) {return a / b;},
      '\u003D': function(a, b) {return b;}
    },
    lastOperator = '\u003D',
    afterEquals = false; // switch to keep track of operators after an equals



// START - Drawing Functions
// canvas styles
ctx.lineWidth = 2;
var buttonRadius = 25;

//attempt at a gradent to resemble shiny plastic of kids toy
var plasticGradient = ctx.createRadialGradient(0, 0, 350, 50, 50, 600);
plasticGradient.addColorStop(0, '#ffeeee');
plasticGradient.addColorStop(0.9, '#ddefbb');
plasticGradient.addColorStop(1, '#ddd');

// draw a rounded rectangle
function roundedRect(xCor, yCor, cornerRadius, length, height) {
  // take into account radius of corner in sides
  var rectLength = length - cornerRadius * 2;
  var rectHeight = height - cornerRadius * 2;
  ctx.save();
  ctx.beginPath();
  //go around counter clockwise from top left
  ctx.translate(xCor, yCor + cornerRadius);
  ctx.moveTo(0, 0);
  ctx.lineTo(0, rectHeight);
  ctx.translate(0, rectHeight);
  ctx.quadraticCurveTo(0, cornerRadius, cornerRadius, cornerRadius);
  ctx.translate(cornerRadius, cornerRadius);
  ctx.lineTo(rectLength, 0);
  ctx.translate(rectLength, 0);
  ctx.quadraticCurveTo(cornerRadius, 0, cornerRadius, -cornerRadius);
  ctx.translate(cornerRadius, -cornerRadius);
  ctx.lineTo(0, -rectHeight);
  ctx.translate(0, -rectHeight);
  ctx.quadraticCurveTo(0, -cornerRadius, -cornerRadius, -cornerRadius);
  ctx.translate(-cornerRadius, -cornerRadius);
  ctx.lineTo(-rectLength, 0);
  ctx.translate(-rectLength, 0);
  ctx.quadraticCurveTo(-cornerRadius, 0, -cornerRadius, cornerRadius);
  ctx.stroke();
  ctx.restore();
}

// draw the calculator buttons
function drawButtons() {
  ctx.font = '24px sans-serif';
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  buttons.forEach(function(button) {
    ctx.beginPath();
    if (button.op) {
      ctx.fillStyle = '#77D13F';
    } else {
      ctx.fillStyle = '#E1163C';
    }

    ctx.arc(button.x, button.y, buttonRadius, 0, 2*Math.PI);
    ctx.stroke();
    ctx.fill();

    ctx.fillStyle = 'white';
    ctx.fillText(button.char, button.x, button.y);
  });

}

function drawScreen() {
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  ctx.fillStyle = 'black';
  ctx.font = '48px Share Tech Mono';
  var numberX = 250, numberY = 140;
  for (var i = displayArr.length - 1; i >= 0; i--) {
    ctx.fillText(displayArr[i], numberX, numberY);
    numberX -= 20;
  }
}

// Draw the calculator
// Called at the start and each time display is changed
function drawCalc() {
  // calculator body
  ctx.beginPath();
  ctx.fillStyle = plasticGradient;
  ctx.moveTo(0, 100);
  ctx.lineTo(10, 450);
  ctx.quadraticCurveTo(150, 500, 290, 450);
  ctx.lineTo(300, 100);
  ctx.quadraticCurveTo(150, 10, 0, 100);
  ctx.fill();
  ctx.stroke();

  // calculator screen frame
  ctx.fillStyle = "#ffe330";
  roundedRect(25, 100, 10, 250, 75);
  ctx.fill();
  ctx.fillStyle = "#4FCCF9";
  roundedRect(35, 110, 5, 230, 55);
  ctx.fill();

  // buttons
  drawButtons();

  // clear button
  ctx.fillStyle = "#ffe330";
  roundedRect(100, 435, 5, 100, 35);
  ctx.fill();
  ctx.fillStyle = 'white';
  ctx.fillText('CLEAR', 150, 455);

  // display digits
  drawScreen();
}
// END Drawing functions


// START - Logic
// which button was pressed
function whichButton(x, y, cx, cy) {
  var dx = x - cx;
  var dy = y - cy;
  return dx * dx + dy * dy <= buttonRadius * buttonRadius;
}

function speak(utter) {
  var sayWhat = utter === '\u002E' ?
    new SpeechSynthesisUtterance('point') : // jshint ignore:line
    new SpeechSynthesisUtterance(utter); // jshint ignore:line

  sayWhat.lang = "en-GB";
  window.speechSynthesis.speak(sayWhat);
}

// calculator logic
function calculate(operator) {
  var displayNum = parseFloat(displayArr.join(''));
  runningTotal = operators[lastOperator](runningTotal, displayNum);
  runningTotal = runningTotal.toPrecision(10).replace(/\.?0+$/,"");
  if (runningTotal > 9999999999) {
    runningTotal = "BIG NUMBER!";
  }
  if (operator === '=') {
    displayArr = runningTotal.toString().split('');
    drawCalc();
  } else {
    displayArr = [];
  }
  lastOperator = operator;
}
//END - Logic



// START - events
// Throttling - http://www.sberry.me/articles/javascript-event-throttling-amp-debouncing
var limiter = true, checkOverButton = false;
calcCanvas.addEventListener('mousemove', function(event) {
  if (limiter) {
    limiter = false;
    var posX = event.pageX - canvasLeft;
    var posY = event.pageY - canvasTop;
    
    buttons.forEach(function(button) {
      if (whichButton(posX, posY, button.x, button.y)) {
        checkOverButton = true;
      }
    });
    if (!checkOverButton) {
      calcCanvas.className = '';
    } else {
      calcCanvas.className = 'pointer';
      checkOverButton = false;
    }
    setTimeout(function() {limiter = true;}, 50);
  }
});

calcCanvas.addEventListener('click', function(event) {
  var clickX = event.pageX - canvasLeft,
      clickY = event.pageY - canvasTop;

  buttons.forEach(function(button) {
    if (whichButton(clickX, clickY, button.x, button.y)) { //was a button clicked?
      if (!button.op) { // if a number is clicked
        if (displayArr.length >= 11) {
          if ('speechSynthesis' in window) {
            speak("Sorry, too many numbers");
          }
        } else {
          if (afterEquals === true) {
            displayArr = [];
            drawCalc();
            afterEquals = false;
          }
          displayArr.push(button.char);
          if ('speechSynthesis' in window) {
            speak(button.char);
          }
          drawCalc();
        }
      } else {
        afterEquals = false;
        calculate(button.char);
        if ('speechSynthesis' in window) {
          speak(button.char);
        }
        if (button.char === '=') {
          if ('speechSynthesis' in window) {
            speak(runningTotal);
          }
          afterEquals = true;
        }
      }
    }
  });
  // clear button
  if ((clickX > 100 && clickX < 200) &&
  (clickY > 435 && clickY < 470)) {
    displayArr = [];
    runningTotal = 0;
    lastOperator = '\u003D';
    afterEquals = false;
    drawCalc();
  }
});

// if speech synthesis api is available change title of page
if ('speechSynthesis' in window){
  document.getElementsByClassName('can-speak')[0].textContent = 'Speaking';
}



// INIT
if (ctx) {
  drawCalc();
}

            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console