Okay, let's enhance the CAPTCHA generation to include letter distortion, shrinking/stretching, varying angles, and reduce the blur to 1px.
The key to achieving this on a Canvas is to use transformation methods like translate, rotate, and scale for each individual character. We'll wrap these transformations with ctx.save() and ctx.restore() to ensure that each character's transformations don't affect the next.
Here's the updated HTML file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Distorted CAPTCHA Generator</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
background-color: #f4f4f4;
color: #333;
}
h1 {
color: #0056b3;
}
button {
padding: 12px 25px;
font-size: 18px;
cursor: pointer;
background-color: #007bff;
color: white;
border: none;
border-radius: 5px;
transition: background-color 0.3s ease;
}
button:hover {
background-color: #0056b3;
}
canvas {
display: none; /* Hidden, used only for generation */
}
p {
margin-bottom: 25px;
}
</style>
</head>
<body>
<h1>Distorted CAPTCHA Image Generator</h1>
<p>
Click the button to generate and download a CAPTCHA image with: <br>
- Black and white background <br>
- Letters randomly colored from gray to black <br>
- Letters distorted, shrunk/stretched, and angled <br>
- 1px blur applied to each letter
</p>
<button id="generateBtn">Generate and Download Distorted CAPTCHA</button>
<canvas id="captchaCanvas"></canvas>
<script>
document.getElementById('generateBtn').addEventListener('click', function() {
const canvas = document.getElementById('captchaCanvas');
const ctx = canvas.getContext('2d');
// Set canvas size
// Increased size to better accommodate distortions
canvas.width = 280; // Width of the image
canvas.height = 70; // Height of the image
// Generate a random string of 6 alphanumeric characters
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let captchaText = '';
for(let i = 0; i < 6; i++) {
captchaText += characters.charAt(Math.floor(Math.random() * characters.length));
}
// Clear canvas and set white background (black and white base)
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Set common font properties. For individual letters, these will be set per letter within the transform context.
ctx.font = '40px Arial'; // Larger base font size to allow for scaling down
ctx.textAlign = 'center'; // Center alignment for text drawing within its transformed space
ctx.textBaseline = 'middle'; // Middle baseline for text drawing
const letters = captchaText.split('');
// Calculate starting X position for the first letter's center, evenly spaced
const xIncrement = canvas.width / (letters.length + 1);
let currentX = xIncrement;
letters.forEach(letter => {
ctx.save(); // Save the current state of the canvas (important before transformations)
// 1. Translate to the center point where the letter will be drawn
// This makes rotations and scaling originate from the letter's center.
ctx.translate(currentX, canvas.height / 2);
// 2. Apply random rotation (-30 to 30 degrees)
const randomAngle = (Math.random() * (Math.PI / 3)) - (Math.PI / 6); // -PI/6 to PI/6 radians (~-30 to +30 degrees)
ctx.rotate(randomAngle);
// 3. Apply random scaling (shrink/stretch from 0.7 to 1.3)
const scaleX = 0.7 + Math.random() * 0.6; // 0.7 to 1.3
const scaleY = 0.7 + Math.random() * 0.6; // 0.7 to 1.3
ctx.scale(scaleX, scaleY);
// 4. Generate a random gray to black color (RGB values from 0 to 128)
const grayValue = Math.floor(Math.random() * 129); // 0 (black) to 128 (mid-gray)
ctx.fillStyle = `rgb(${grayValue}, ${grayValue}, ${grayValue})`;
// 5. Apply 1px blur
ctx.filter = 'blur(1px)';
// 6. Draw the letter at the current translated origin (0,0)
// Because we set textAlign and textBaseline to 'center'/'middle' and translated,
// drawing at 0,0 effectively centers the letter within its transformed space.
ctx.fillText(letter, 0, 0);
ctx.restore(); // Restore the canvas state to what it was before this letter's transformations
currentX += xIncrement; // Move X position for the next letter
});
// Reset filter for any subsequent drawing operations (though none here)
ctx.filter = 'none';
// Convert canvas to a downloadable image
const dataURL = canvas.toDataURL('image/png');
const link = document.createElement('a');
link.href = dataURL;
link.download = `captcha_${captchaText}.png`; // Tag the filename with the characters
link.click(); // Trigger the download
});
</script>
</body>
</html>
Key Changes and How They Work:
-
Canvas Size:
- Increased
canvas.width to 280 and canvas.height to 70 to provide more space for the distorted characters without them overlapping too much or going out of bounds.
-
Per-Letter Transformations:
ctx.save() and ctx.restore(): These are crucial. ctx.save() creates a snapshot of the current canvas state (including transformations, fillStyle, font, etc.). ctx.restore() reverts the canvas to the last saved state. This ensures that the transformations (translate, rotate, scale) applied to one letter don't affect the subsequent letters.
ctx.translate(currentX, canvas.height / 2): Before drawing each letter, the canvas's origin ((0,0)) is moved to the calculated center point for that specific letter. This makes it easy to rotate and scale around the letter's own center.
ctx.rotate(randomAngle): A random angle between -30 and +30 degrees (converted to radians) is applied.
ctx.scale(scaleX, scaleY): Random scale factors (between 0.7 and 1.3) are applied independently to the X and Y axes, causing letters to shrink or stretch.
ctx.fillText(letter, 0, 0): After translate, rotate, and scale, the letter is drawn at (0,0). Because ctx.textAlign is set to 'center' and ctx.textBaseline to 'middle', the letter is perfectly centered within its now-transformed local coordinate system.
-
Blur:
ctx.filter = 'blur(1px)': The blur amount is changed to 1px as requested. This filter is also applied within the save()/restore() block, ensuring it only affects the current letter.
-
Font Size and Alignment:
- The base
ctx.font is increased to 40px before scaling down, giving more room for variation.
ctx.textAlign = 'center' and ctx.textBaseline = 'middle' are set to make positioning during transformations easier.
How to Use:
- Save the entire code block above into a file named, for example,
distorted_captcha.html.
- Open this
.html file in any modern web browser (Chrome, Firefox, Edge, Safari, etc.).
- Click the "Generate and Download Distorted CAPTCHA" button.
- A PNG image file (e.g.,
captcha_xyz789.png) will be downloaded, containing your newly generated distorted CAPTCHA.
You'll notice that each time you generate, the letters will have different sizes, rotations, positions, and shades of gray, making them more challenging to read than the previous version!