Captcha Generator using HTML, CSS, JavaScript |
Bots are a headache for every website. They reduce the performance of the website and affect your website's SEO. To prevent them captcha was introduced. A captcha can filter bots and helps you to improve SEO. Its robust algorithm makes it efficiently finds the difference between humans and bots. Today, we will create a captcha generator using HTML, CSS, and JavaScript.
What is Captcha?
Captcha is a method to determine whether it is a human or not. Captcha contains numbers and letters in an image. Visiter needs to fill in the text in the input box shown in the captcha image. It is easy for humans but difficult for machines.
Why do we need a captcha?
Automated software, or bots, can perform various harmful activities. A captcha system helps to distinguish between human and machine users by protecting the website from such activities. There are different advantages of this system. Some are:-
-
Financial Institutes: It helps us to prevent unhealthy transactions. It ensures that all economic activities should be done by humans.
-
Prevent unauthorized registrations: Captcha prevents bots from unauthorized accounts in the system.
It's time to create our tool. So, let's get started!
Creating a captcha generator using HTML, CSS, and JavaScript
Now, we understand the importance of the Captcha generator. Let's learn how to create a captcha generator. First, make a folder for this project.
Make these files:-
- HTML:- index.html
- CSS:- style.css
- JavaScript:- index.js
HTML Section
The first step is to create an HTML boiler template. Now, create a div element and add some of these elements to the div. such as:-
- Canvas:- Create a canvas element to display letters as a captcha.
- Reload button:- Create a button to reload the captcha and clear text in the input box.
- Input Box:- An input box to fill the captcha by the user.
- Submit button:- A submit button to verify the captcha.
Add a font awesome CDN in the header of the HTML code. You can see the code given below.
<html lang="en"> <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"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" /> <link rel="stylesheet" href="style.css"> <title>captcha generator</title> </head> <body> <div class="container"> <div class="wrapper"><canvas id="canvas" width="200" height="70"></canvas> <button id="reload_btn"><i class="fa-solid fa-rotate-right"></i></button> </div> <input type="text" id="user_input" placeholder="Enter Captcha"> <button id="submit_btn">Submit</button> </div> <script src="index.js"></script> </body> </html>
CSS Section
It is time to give some style to our project. First, we will import Google Fonts with the help of google fonts CDN. Then, declare some properties to make a UI layout of the document. Here is the code to style this generator.
@import url('https://fonts.googleapis.com/css2?family=Roboto+Mono:wght@500&display=swap'); :root{ --primary_color:rgba(71, 45, 255, 1); } * { margin: 0; padding: 0; box-sizing: border-box; } body { width: 100%; height: 100vh; background: linear-gradient(90deg, #a1c4fd 0%, #c2e9fb 100%); } .container { width: 32rem; background-color: #fff; padding: 5rem; border-radius: 0.6rem; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); box-shadow: 0 1rem 2rem rgba(0, 0, 0, 0.25); } .wrapper { display: flex; align-content: center; justify-content: space-between; margin: 1rem 0; } canvas { border: 1px solid rgba(0, 0, 0, 0.5); border-radius: 0.4rem; } #reload_btn { font-size: 26px; width: 4.6rem; background-color: var(--primary_color); border: none; border-radius: 0.4rem; color: #fff; /* height: 76px; */ } #user_input{ font-family: "Roboto Mono", monospace; font-size: 1.05rem; padding: 1rem 0.7rem; border: 1px solid rgba(0, 0, 0, 0.5); border-radius: 0.4rem; width: 100%; outline: none; } #user_input:hover, #user_input:focus{ border: 1px solid var(--primary_color); } #submit_btn{ width: 100%; background-color: var(--primary_color); color: #fff; font-size: 1.5rem; border: none; margin-top: 1rem; padding: 0.8rem 0; border-radius: 0.4rem; font-family: "Roboto Mono", monospace; }
JavaScript Section
It is the most essential part of our application. Our application depends on this JavaScript code. First, we create a function trigger after loading the window. We will write all code in this function. Then we get all the elements. Here is an example.
window.addEventListener("load", () => { let canvas = document.getElementById("canvas") let reload_btn = document.getElementById("reload_btn") let user_input = document.getElementById("user_input") let submit_btn = document.getElementById("submit_btn") let text = "" })
Create a function textGenerator()
to generate text that will
display as a captcha. This function has a variable to store text. Then, a loop
generates nine random letters. This contains lowercase letters, uppercase
letters, and numbers. At last, this function returns generated text.
// Generate text function textGenerator() { let generatedText = "" // String.fromcharcode gives ASCII values from given number, total 9 letters hence loop of 3 for (let i = 0; i < 3; i++) { // 65-90 numbers are capital letters generatedText += String.fromCharCode(randomNumber(65, 90)) // 97-122 are small letters generatedText += String.fromCharCode(randomNumber(97, 122)) // 48-57 are numbers generatedText += String.fromCharCode(randomNumber(48, 57)) } return generatedText}
Now, create a function randomNumber()
. This function takes two
values and returns a random number between the given numbers. We will use this
function to provide random color to the letters of the captcha. You can also
see it in the example.
// Generating random numbers function randomNumber(min, max) { return Math.floor(Math.random() * (max - min + 1) + min) }
We will display text as a canvas. We should create a function to draw text on
the canvas. So, make a function drawTextOnCanvas(text)
. This
function takes generated text as an argument and draws this text on the
canvas.
// Drawind text on canvas function drawTextOnCanvas(text) { let ctx = canvas.getContext("2d") // clear canvas ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height) // array of text color const textColor = ["rgba(0,0,0,0.8)", "rgba(71, 45, 255, 1)"] // space b/w lettes const letterSpace = 150 / text.length // loop through string for (let i = 0; i < text.length; i++) { // definding initial space for x axis const xInitialSpace = 25 ctx.font = "20px Roboto Mono" // set text color ctx.fillStyle = textColor[randomNumber(0, 1)] ctx.fillText(text[i], xInitialSpace + i * letterSpace, randomNumber(25, 40), 100) } }
Creating a function reloadCaptcha()
. This function will reload
the captcha and clears the input box value. We call this function by clicking
reload button. So, we wrap this function in an event listener. We also call
this function while the webpage reloads. Here is the code.
// initial function function reloadCaptcha() { // clearing input user_input.value = "" text = textGenerator() // randomize the text so that everytime the position of numbers and small letters is random text = [...text].sort(() => Math.random() - 0.5).join("") drawTextOnCanvas(text) } // calling reloadCaptcha function on reload button reload_btn.addEventListener("click", () => reloadCaptcha()) // calling reloadCaptcha function on reload button reloadCaptcha()
In the final step, we validate our captcha at the time of submission. We make an event listener, triggers on clicking submit button. In this event listener, a function checks whether the entered text matches the given captcha.
// validating captcha on submit button submit_btn.addEventListener("click", () => { if (user_input.value === text) { alert("Success!") reloadCaptcha() } else { alert("Invalid") reloadCaptcha() } })
Complete Javascript source code
We understand this code step-wise. You can get the complete source code of this javascript file below.
window.addEventListener("load", () => { let canvas = document.getElementById("canvas") let reload_btn = document.getElementById("reload_btn") let user_input = document.getElementById("user_input") let submit_btn = document.getElementById("submit_btn") let text = "" // Generate text function textGenerator() { let generatedText = "" // String.fromcharcode gives ASCII values from given number, total 9 letters hence loop of 3 for (let i = 0; i < 3; i++) { // 65-90 numbers are capital letters generatedText += String.fromCharCode(randomNumber(65, 90)) // 97-122 are small letters generatedText += String.fromCharCode(randomNumber(97, 122)) // 48-57 are numbers generatedText += String.fromCharCode(randomNumber(48, 57)) } return generatedText } // Generating random numbers function randomNumber(min, max) { return Math.floor(Math.random() * (max - min + 1) + min) } // console.log(textGenerator()); // Drawing text on canvas function drawTextOnCanvas(text) { let ctx = canvas.getContext("2d") // clear canvas ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height) // array of text color const textColor = ["rgba(0,0,0,0.8)", "rgba(71, 45, 255, 1)"] // space b/w lettes const letterSpace = 150 / text.length // loop through string for (let i = 0; i < text.length; i++) { // definding initial space for x axis const xInitialSpace = 25 ctx.font = "20px Roboto Mono" // set text color ctx.fillStyle = textColor[randomNumber(0, 1)] ctx.fillText(text[i], xInitialSpace + i * letterSpace, randomNumber(25, 40), 100) } } // initial function function reloadCaptcha() { // clearing input user_input.value = "" text = textGenerator() // randomize the text so that everytime the position of numbers and small letters is random text = [...text].sort(() => Math.random() - 0.5).join("") drawTextOnCanvas(text) } // calling reloadCaptcha function on reload button reload_btn.addEventListener("click", () => reloadCaptcha()) // calling reloadCaptcha function on reload button reloadCaptcha() // validating captcha on submit button submit_btn.addEventListener("click", () => { if (user_input.value === text) { alert("Success!") reloadCaptcha() } else { alert("Invalid") reloadCaptcha() } }) })
That's it! We completed our captcha generator. You can customize it to your requirements.
Conclusion
Ultimately, every website should implement captchas as a security measure. They prevent automated software from harmful activities. Creating a captcha generator using HTML, CSS, and JavaScript is a simple and effective way to implement captchas on websites. Following the instructions outlined in the article, you can create a robust and secure captcha for your website.