提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
Visual Calculator Based on JavaScript
Introduction
This blog is written to show the process of how to make a calculator based on JavaScript and CSS and HTML.
Information table
The Link Your Class | https://bbs.csdn.net/forums/ssynkqtd-04 |
---|---|
Link of Requirement of This Assignment | https://bbs.csdn.net/topics/617332156 |
Aim of This Assignment | calculator with a visual interface |
MU STU ID and FZU STU ID | 21124663_832101103 |
Link to the finished project code:https://github.com/Iwtbs27/HW/tree/main
PSP form
Personal Software Process Stages | Estimated Time(minutes) | Actual Time(minutes) |
---|---|---|
Planning | 30 | 30 |
• Estimate | 30 | 30 |
Development | 30 | 30 |
• Analysis | 30 | 30 |
• Design Spec | 30 | 30 |
• Design Review | 30 | 50 |
• Coding Standard | 30 | 30 |
• Design | 30 | 30 |
• Coding | 30 | 40 |
• Code Review | 30 | 30 |
• Test | 30 | 30 |
Reporting | 30 | 50 |
• Test Repor | 30 | 30 |
• Size Measurement | 30 | 30 |
• Postmortem & Process Improvement Plan | 30 | 30 |
Sum | 450 | 500 |
Problem-Solving Ideas
- In this project, the final aim is to make a calculator that include
mumber input and operator input and some funciton lick sin and cos
also should be considered. - So, We can use HTML to write exterior appearance and use css to
embalish it and use JavaScript to design logic part.
The process of design and implementation
User Interface Initialization:
- When the page loads, HTML and CSS ensure the basic layout and styling of the calculator.
- The JavaScript script (“script.js” file) initializes the buttons and
display screen elements on the page for subsequent interactions.
User Input:
- Users can input mathematical expressions by clicking on the
calculator’s number buttons, operator buttons, and other functional
buttons like trigonometric functions or exponentials. - The inputted content is displayed on the calculator’s screen (with
the element ID “display”).
Calculator Logic Processing:
- Event listeners in the JavaScript script monitor user button clicks.
- When users click a button, the corresponding handling function
performs different operations based on the button type.
Expression Handling:
- If users click number buttons, operator buttons, parentheses, etc.,
they are added to the expression displayed on the screen.
Handling Special Functions:
- If users click special function buttons like “sin,” “cos,” “tan,”
“exp,” etc., the corresponding functions or operators are added to
the expression.
Handling the “=” Button:
- When users click the equals (=) button, the calculator performs the
following actions: It replaces operators and special functions in the
expression with their equivalent JavaScript representations (e.g.,
replacing “sin(” with “Math.sin(”). It converts angles from degrees
to radians for trigonometric calculations. It uses the eval()
function to calculate the result of the expression. If the
calculation is successful, the result is displayed on the screen.
Error Handling:
- If an error occurs during calculation (e.g., division by zero or
expression format error), an error message is displayed on the
screen.
Clearing and Deleting:
- Users can clear the content displayed on the screen by clicking the
“C” button, or they can delete the last character by clicking the “<”
button.
Theme Switching:
- Users have the option to switch between different themes for the
calculator, transitioning between dark and light themes or vice
versa.
Coding
HTML
The HTML document is responsible for creating the user interface of the electronic calculator. It defines the layout, buttons, display screen, theme toggle button, and other elements of the calculator, allowing users to interact with the calculator through a web browser.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Huihuang's Calculator</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div class="container">
<div class="calculator dark">
<div class="theme-toggler active">
<i class="toggler-icon"></i>
</div>
<div class="display-screen">
<div id="display"></div>
</div>
<div class="buttons">
<table>
<tr>
<td><button class="btn-operator" id="clear">C</button></td>
<td><button class="btn-operator" id="/">÷</button></td>
<td><button class="btn-operator" id="*">×</button></td>
<td><button class="btn-operator" id="sin">sin</button></td>
<td><button class="btn-operator" id="backspace"><</button></td>
</tr>
<tr>
<td><button class="btn-number" id="7">7</button></td>
<td><button class="btn-number" id="8">8</button></td>
<td><button class="btn-number" id="9">9</button></td>
<td><button class="btn-operator" id="cos">cos</button></td>
<td><button class="btn-operator" id="-">-</button></td>
</tr>
<tr>
<td><button class="btn-number" id="4">4</button></td>
<td><button class="btn-number" id="5">5</button></td>
<td><button class="btn-number" id="6">6</button></td>
<td><button class="btn-operator" id="tan">tan</button></td>
<td><button class="btn-operator" id="+">+</button></td>
</tr>
<tr>
<td><button class="btn-number" id="1">1</button></td>
<td><button class="btn-number" id="2">2</button></td>
<td><button class="btn-number" id="3">3</button></td>
<td><button class="btn-operator" id="^">^</button></td>
<td rowspan="2"><button class="btn-equal" id="equal">=</button></td>
</tr>
<tr>
<td><button class="btn-operator" id="(">(</button></td>
<td><button class="btn-number" id="0">0</button></td>
<td><button class="btn-operator" id=")">)</button></td>
<td><button class="btn-operator" id="exp">exp</button></td>
</tr>
</table>
</div>
</div>
</div>
<script src="./script.js"></script>
</body>
</html>
CSS
The CSS stylesheet defines the appearance and style of the calculator, including the look, colors, sizes, fonts, and more of the buttons. It ensures that the calculator maintains a consistent appearance across various screen sizes and devices, providing visual aesthetics and user-friendliness.
*{
margin: 0;
padding: 0;
box-sizing: border-box;
outline: 0;
transition: all 0.5s ease;
}
body{
font-family: sans-serif;
}
a{
text-decoration: none;
color: #fff;
}
body{
background-image: linear-gradient(to bottom right, rgba(79, 51, 176, 1), rgba(210, 53, 165));
}
.container{
height: 100vh;
width: 100vw;
display: grid;
place-items: center;
}
.calculator{
position: relative;
height: auto;
width: auto;
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 30px #000;
}
.theme-toggler{
position: absolute;
top: 30px;
right: 30px;
color: #fff;
cursor: pointer;
z-index: 1;
}
.theme-toggler.active{
color: #333;
}
.theme-toggler.active::before{
background-color: #fff;
}
.theme-toggler::before{
content: '';
height: 30px;
width: 30px;
position: absolute;
top: 50%;
transform: translate(-50%, -50%);
border-radius: 50%;
background-color: #333;
z-index: -1;
}
#display{
margin: 0 10px;
height: 150px;
width: auto;
max-width: 270px;
display: flex;
align-items: flex-end;
justify-content: flex-end;
font-size: 30px;
overflow-x: scroll;
}
#display::-webkit-scrollbar{
display: block;
height: 3px;
}
button{
height: 60px;
width: 60px;
border: 0;
border-radius: 30px;
margin: 5px;
font-size: 20px;
cursor: pointer;
transition: all 200ms ease;
}
button:hover{
transform: scale(1.1);
}
button#equal{
height: 130px;
}
/* Daytime theme */
.calculator{
background-color: #fff;
}
.calculator #display{
color: #0a1e23;
}
.calculator button#clear{
background-color: #ffd5d8;
color: #fc4552;
}
.calculator button.btn-number{
background-color: #c3eaff;
color: #000;
}
.calculator button.btn-operator{
background-color: #ffd0fd;
color: #f967f3;
}
.calculator button.btn-equal{
background-color: #adf9e7;
color: #000;
}
/* Nighttime theme */
.calculator.dark{
background-color: #071115;
}
.calculator.dark #display{
color: #f8fafd;
}
.calculator.dark button#clear{
background-color: #2d191e;
color: #bd3740;
}
.calculator.dark button.btn-number{
background-color: #1b2f38;
color: #f8fafb;
}
.calculator.dark button.btn-operator{
background-color: #2e1f39;
color: #aa00a4;
}
.calculator.dark button.btn-equal{
background-color: #223323;
color: #fff;
}
JavaScript
The JavaScript script adds interactivity and functionality to the calculator. It initializes the buttons and display screen elements, listens for user click events, and performs mathematical calculations and special functions based on user input. JavaScript also handles error cases, such as division by zero or expression format errors, as well as clearing and deleting operations. Additionally, it allows users to toggle the calculator’s theme, changing its appearance.
Process
const display = document.querySelector('#display');
const buttons = document.querySelectorAll('button');
buttons.forEach((item) => {
item.onclick = () => {
if (item.id == 'clear') {
display.innerText = '';
} else if (item.id == 'backspace') {
let string = display.innerText.toString();
display.innerText = string.substr(0, string.length - 1);
} else if (item.id == 'equal') {
const expression = display.innerText;
if (expression.includes('sin') || expression.includes('cos') || expression.includes('tan') || expression.includes('^')) {
// Handle expressions containing special functions
try {
const result = calculate(expression);
display.innerText = result;
} catch (error) {
display.innerText = `Error: ${error.message}`;
}
} else {
// Directly calculate regular expressions
try {
const result = eval(expression);
display.innerText = result;
} catch (error) {
display.innerText = `Error: ${error.message}`;
}
}
} else if (item.id == 'exp') {
// Handle exponentiation operation
display.innerText += '^';
} else if (item.id == 'sin') {
// Handle sine operation
display.innerText += 'sin(';
} else if (item.id == 'cos') {
// Handle cosine operation
display.innerText += 'cos(';
} else if (item.id == 'tan') {
// Handle tangent operation
display.innerText += 'tan(';
} else {
display.innerText += item.id;
}
}
});
function calculate(expression) {
// Calculate mathematical operations in the expression, including sin, cos, tan, and exponentiation
expression = expression.replace(/sin\(([^)]+)\)/g, (match, angle) => {
const radians = (parseFloat(angle) * Math.PI) / 180;
return Math.sin(radians).toFixed(3);
});
expression = expression.replace(/cos\(([^)]+)\)/g, (match, angle) => {
const radians = (parseFloat(angle) * Math.PI) / 180;
return Math.cos(radians).toFixed(3);
});
expression = expression.replace(/tan\(([^)]+)\)/g, (match, angle) => {
const radians = (parseFloat(angle) * Math.PI) / 180;
return Math.tan(radians).toFixed(3);;
});
expression = expression.replace(/\^/g, '**');
return eval(expression);
}
const themeToggleBtn = document.querySelector('.theme-toggler');
const calculator = document.querySelector('.calculator');
const toggleIcon = document.querySelector('.toggler-icon');
let isDark = true;
themeToggleBtn.onclick = () => {
calculator.classList.toggle('dark');
themeToggleBtn.classList.toggle('active');
isDark = !isDark;
}
Result Displaying
Summary
This project is a web-based electronic calculator that allows users to perform mathematical calculations and includes features such as basic arithmetic operations, trigonometric functions (sin, cos, tan), exponentiation, and the ability to switch between degree and radian modes for trigonometric calculations. The calculator has a user-friendly interface with buttons for input and a display screen to show the entered expressions and results.
From this project, I have gained a preliminary understanding of the basics of visualization and web development, including knowledge exploration and learning. This has been immensely helpful to me.