Javascript in development

JavaScript in development (I)

1. Use canvas to realize the function of generating verification code

The html file of this article is shown in the figure below, and the JS file that implements the verification code is verify js

<!DOCTYPE html>
<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">
  <title>Verification Code</title>
</head>

<body>
  <canvas id="vetifyCanvas" width="100" height="40"></canvas>
  <script src="./verify.js"></script>
</body>

</html>

1.1 set the background to random color

const canvas = document.getElementById('vetifyCanvas');
const w = canvas.width;
const h = canvas.height;
const context = canvas.getContext('2d');

context.fillStyle = randomColor(0, 155); // Set the background to a random color
context.fillRect(0, 0, w, h); // draw rectangle


function randomNum(min, max) {
  return Math.floor(Math.random() * (max - min) + min); // Generate a random number
}

function randomColor(min, max) {
  const r = randomNum(min, max);
  const g = randomNum(min, max);
  const b = randomNum(min, max);
  return 'rgb(' + r + ', ' + g + ', ' + b + ')';
}

1.2 generate 4-bit random verification code

const canvas = document.getElementById('vetifyCanvas');
const w = canvas.width;
const h = canvas.height;
const context = canvas.getContext('2d');

let text = []; //Used to store random characters
let verifyCode = []; // Used to store verification code

context.fillStyle = randomColor(0, 155); // Set the background to a random color
context.fillRect(0, 0, w, h); // draw rectangle

addText('a', 'z');
addText('A', 'Z');
addText('0', '9');

generateCode(4);
console.log(verifyCode);

function randomNum(min, max) {
  return Math.floor(Math.random() * (max - min) + min); // Generate a random number
}

function randomColor(min, max) {
  const r = randomNum(min, max);
  const g = randomNum(min, max);
  const b = randomNum(min, max);
  return 'rgb(' + r + ', ' + g + ', ' + b + ')';
}

function addText(start, end) { // Add characters for random
  for (let i = start.charCodeAt(); i <= end.charCodeAt(); i += 1) { // ASCII values are obtained from ASCII characters
    text.push(String.fromCharCode(i)); // ASCII characters are obtained from ASCII values
  }
}

function generateCode(num) { // Generate verification code
  for (let i = 0; i < num; i++) {
    let index = randomNum(0, text.length - 1);
    verifyCode.push(text[index]);
  }

}

1.3 draw the generated verification code

const canvas = document.getElementById('vetifyCanvas');
const w = canvas.width;
const h = canvas.height;
const context = canvas.getContext('2d');

let text = []; //Used to store random characters
let verifyCode = []; // Used to store verification code

context.fillStyle = randomColor(0, 255); // Set the background to a random color
context.fillRect(0, 0, w, h); // draw rectangle
context.textBaseline = "middle";

addText('a', 'z');
addText('A', 'Z');
addText('0', '9');

generateCode(4);

function randomNum(min, max) {
  return Math.floor(Math.random() * (max - min) + min); // Generate a random number
}

function randomColor(min, max) {
  const r = randomNum(min, max);
  const g = randomNum(min, max);
  const b = randomNum(min, max);
  return 'rgb(' + r + ', ' + g + ', ' + b + ')';
}

function addText(start, end) { // Add characters for random
  for (let i = start.charCodeAt(); i <= end.charCodeAt(); i += 1) { // ASCII values are obtained from ASCII characters
    text.push(String.fromCharCode(i)); // ASCII characters are obtained from ASCII values
  }
}

function generateCode(num) { // Generate verification code
  for (let i = 0; i < num; i++) {
    let index = randomNum(0, text.length - 1);
    verifyCode.push(text[index]);
    let x = (w / 5) * i; // Used to control the coordinates to start writing
    let y = h / 2;

    context.font = randomNum(h / 2, h) + 'px SimHei'; // Randomly generated font size
    context.fillStyle = randomColor(100, 200); // Randomly generated font color

    context.translate(x, y); // Set coordinate origin
    context.fillText(text[index], 0, 0); // write
    context.translate(-x, -y); // Restore coordinate origin
  }

}

After writing, why restore the coordinate origin? After writing a word here, its coordinates will follow to the lower right corner, so if you don't return to the starting point, you will write an oblique line of words, and you can see the result by increasing the width and height of the canvas alone. Analysis may be wrong, please forgive me.

1.4 add special effects (text shadow and rotation)

const canvas = document.getElementById('vetifyCanvas');
const w = canvas.width;
const h = canvas.height;
const context = canvas.getContext('2d');

let text = []; //Used to store random characters
let verifyCode = []; // Used to store verification code

context.fillStyle = randomColor(0, 255); // Set the background to a random color
context.fillRect(0, 0, w, h); // draw rectangle
context.textBaseline = "middle";

addText('a', 'z');
addText('A', 'Z');
addText('0', '9');

generateCode(4);

function randomNum(min, max) {
  return Math.floor(Math.random() * (max - min) + min); // Generate a random number
}

function randomColor(min, max) {
  const r = randomNum(min, max);
  const g = randomNum(min, max);
  const b = randomNum(min, max);
  return 'rgb(' + r + ', ' + g + ', ' + b + ')';
}

function addText(start, end) { // Add characters for random
  for (let i = start.charCodeAt(); i <= end.charCodeAt(); i += 1) { // ASCII values are obtained from ASCII characters
    text.push(String.fromCharCode(i)); // Obtain ASCII characters from ASCII values
  }
}

function generateCode(num) { // Generate verification code
  for (let i = 0; i < num; i++) {
    let index = randomNum(0, text.length - 1);
    verifyCode.push(text[index]);

    let x = (w / 5) * i; // Used to control the coordinates to start writing
    let y = h / 2;

    context.shadowOffsetX = randomNum(-3, 3);
    context.shadowOffsetY = randomNum(-3, 3);
    context.shadowBlur = randomNum(-3, 3);
    context.shadowColor = 'rgba(0, 0, 0, 0.3)';

    context.font = randomNum(h / 2, h) + 'px SimHei'; // Randomly generated font size
    context.fillStyle = randomColor(100, 200); // Randomly generated font color

    const deg = randomNum(-20, 20);

    context.translate(x, y); // Set coordinate origin and rotation angle
    context.rotate(deg * Math.PI / 180);
    context.fillText(text[index], 0, 0); // write
    context.translate(-x, -y); // Restore coordinate origin and rotation angle
    context.rotate(-deg * Math.PI / 180);
  }

}

1.5 add interference lines and interference points

const canvas = document.getElementById('vetifyCanvas');
const w = canvas.width;
const h = canvas.height;
const context = canvas.getContext('2d');

let text = []; //Used to store random characters
let verifyCode = []; // Used to store verification code

context.fillStyle = randomColor(0, 255); // Set the background to a random color
context.fillRect(0, 0, w, h); // draw rectangle
context.textBaseline = "middle";

addText('a', 'z');
addText('A', 'Z');
addText('0', '9');

generateCode(4);

ganrao();

function randomNum(min, max) {
  return Math.floor(Math.random() * (max - min) + min); // Generate a random number
}

function randomColor(min, max) {
  const r = randomNum(min, max);
  const g = randomNum(min, max);
  const b = randomNum(min, max);
  return 'rgb(' + r + ', ' + g + ', ' + b + ')';
}

function addText(start, end) { // Add characters for random
  for (let i = start.charCodeAt(); i <= end.charCodeAt(); i += 1) { // ASCII values are obtained from ASCII characters
    text.push(String.fromCharCode(i)); // ASCII characters are obtained from ASCII values
  }
}

function generateCode(num) { // Generate verification code
  for (let i = 0; i < num; i++) {
    let index = randomNum(0, text.length - 1);
    verifyCode.push(text[index]);

    let x = (w / 5) * i; // Used to control the coordinates to start writing
    let y = h / 2;

    context.shadowOffsetX = randomNum(-3, 3);
    context.shadowOffsetY = randomNum(-3, 3);
    context.shadowBlur = randomNum(-3, 3);
    context.shadowColor = 'rgba(0, 0, 0, 0.3)';

    context.font = randomNum(h / 2, h) + 'px SimHei'; // Randomly generated font size
    context.fillStyle = randomColor(100, 200); // Randomly generated font color

    const deg = randomNum(-20, 20);

    context.translate(x, y); // Set coordinate origin and rotation angle
    context.rotate(deg * Math.PI / 180);
    context.fillText(text[index], 0, 0); // write
    context.translate(-x, -y); // Restore coordinate origin and rotation angle
    context.rotate(-deg * Math.PI / 180);
  }

}

function ganrao() {
  // Draw interference line
  // for (var i = 0; i < 4; i++) {
  //   context.strokeStyle = randomColor(40, 180);
  //   context.beginPath();
  //   context.moveTo(randomNum(0, w), randomNum(0, h));
  //   context.lineTo(randomNum(0, w), randomNum(0, h));
  //   context.stroke();
  // }
    
  // Draw interference points
  for (var i = 0; i < w / 4; i++) {
    context.fillStyle = randomColor(0, 255);
    context.beginPath();
    context.arc(randomNum(0, w), randomNum(0, h), 1, 0, 2 * Math.PI);
    context.fill();
  }
}

effect:

1.6 add the function of refreshing by clicking

Context save(); And context restore(); To achieve the effect of emptying the canvas and redrawing

Full code: Verification code (codepen.io)

2. Generate 32-bit random code

During the project meeting, I heard that the id in the data table should use the general method of generating 32-bit random code instead of int + self increment. I want to try to generate 32-bit random code by myself.

First, you need to get an array of characters used to generate random codes. Here, you can use hand tapping, but it's too tired. You can also use the method when generating the verification code. Because the characters of js cannot be self incremented, you can use the charCodeAt() function to convert the characters into ASCII values, and then perform the self incrementing operation. Of course, the values obtained in each traversal are ASCII values, so you can use string The fromcharcode() function converts ASCII values into ASCII characters.

The specific implementation is as follows:

function getContent(start, end) {
  let arr = [];
  for (let i = start.charCodeAt(); i <= end.charCodeAt(); i++) {
    arr.push(String.fromCharCode(i));
  }
  return arr;
}

After the characters used to generate random codes are obtained, 32-bit random codes can be generated directly through the random function random().

function getRandom() {
  let arr = [];
  arr = arr.concat(getContent('a', 'z'));
  arr = arr.concat(getContent('0', '9'));

  let id = '';
  for (let i = 0; i < 32; i++) {
    id += arr[parseInt(Math.random() * 36)];
  }
  console.log(id);
}

function getContent(start, end) {
  let arr = [];
  for (let i = start.charCodeAt(); i <= end.charCodeAt(); i++) {
    arr.push(String.fromCharCode(i));
  }
  return arr;
}

getRandom();

The complete implementation is as follows:

function getRandom() {
  let arr = [];
  arr = arr.concat(getContent('a', 'z'));
  arr = arr.concat(getContent('0', '9'));

  let id = '';
  for (let i = 0; i < 32; i++) {
    id += arr[parseInt(Math.random() * 36)];
  }
  console.log(id);
}

function getContent(start, end) {
  let arr = [];
  for (let i = start.charCodeAt(); i <= end.charCodeAt(); i++) {
    arr.push(String.fromCharCode(i));
  }
  return arr;
}

getRandom();

Possible common method: record it. There may be better methods to update after discovery.

function getContent(start, end) {
  let arr = [];
  for (let i = start.charCodeAt(); i <= end.charCodeAt(); i++) {
    arr.push(String.fromCharCode(i));
  }
  return arr;
}

Original address (personal blog): JavaScript in development (I) -- red, blue and purple

Reference link: JS realizes the function of picture verification code - user input verification code - vickylinj - blog Garden (cnblogs.com)

Keywords: Javascript Front-end

Added by jcombs_31 on Sat, 11 Dec 2021 08:39:48 +0200