在網站中我們很常見到形形色色的驗證碼,今天我們來用JS來生成一個隨機的二維碼。
我們需要用到canvas
來進行驗證碼的繪製
什麼是Canvas
HTML5 的 canvas 元素使用 JavaScript 在網頁上繪製圖像。
畫布是一個矩形區域,您可以控制其每一像素。
canvas 擁有多種繪製路徑、矩形、圓形、字符以及添加圖像的方法。
點擊學習
思路
我們要做的二維碼首先要有隨機的數字,其次就是要有隨機的位置。
HTML
<canvas id="canvas" style="border: 1px solid red; width: 80px; height: 40px;"></canvas>
JS
function getVerification() { //二維碼
var ctx = document.getElementById("canvas").getContext("2d");
// 清空畫布
ctx.clearRect(0,0, 400, 400);
// 設置字體
ctx.font = "128px bold 黑體";
// 設置垂直對齊方式
ctx.textBaseline = "top";
// 設置顏色
ctx.fillStyle = randomColor();
// 繪製文字(參數:要寫的字,x座標,y座標)
ctx.fillText(getRandomNum(10), 0, getRandomNum(50));
ctx.fillStyle = randomColor();
ctx.fillText(getRandomNum(10), 50, getRandomNum(50));
ctx.fillStyle = randomColor();
ctx.fillText(getRandomNum(10), 100, getRandomNum(50));
ctx.fillStyle = randomColor();
ctx.fillText(getRandomNum(10), 150, getRandomNum(50));
}
- 我們使用
ctx.fillStyle = randomColor();
來設置隨機的顏色,每寫一個數字換一個顏色,randomColoe()
函數代碼如下,可以隨機生成十六進制顏色碼。
function randomColor() {
var colorValue = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f";
var colorArray = colorValue.split(",");
var color = "#";
for (var i = 0; i < 6; i++) {
color += colorArray[Math.floor(Math.random() * 16)];
}
return color;
}
- 我們使用
getRandomNum()
來獲取隨機顯示的數字和隨機每次字體的y
軸方向的位置。驗證碼的每個數字分別進行獲取。傳入的參數n
來確定隨機數範圍。代碼如下:
function getRandomNum(n){
return parseInt(Math.random() * n);
}
完整代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>2</title>
</head>
<body>
<canvas id="canvas" style="border: 1px solid red; width: 80px; height: 40px;"></canvas>
<span id="yanzhengma"></span><button onclick="getVerification()">看不清</button>
<script>
function randomColor() {
var colorValue = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f";
var colorArray = colorValue.split(",");
var color = "#";
for (var i = 0; i < 6; i++) {
color += colorArray[Math.floor(Math.random() * 16)];
}
return color;
}
function getRandomNum(n){
return parseInt(Math.random() * n);
}
function getVerification() {
var ctx = document.getElementById("canvas").getContext("2d");
ctx.clearRect(0,0, 400, 400);
// 設置字體
ctx.font = "128px bold 黑體";
// 設置垂直對齊方式
ctx.textBaseline = "top";
// 設置顏色
ctx.fillStyle = randomColor();
// 繪製文字(參數:要寫的字,x座標,y座標)
ctx.fillText(getRandomNum(10), 0, getRandomNum(50));
ctx.fillStyle = randomColor();
ctx.fillText(getRandomNum(10), 50, getRandomNum(50));
ctx.fillStyle = randomColor();
ctx.fillText(getRandomNum(10), 100, getRandomNum(50));
ctx.fillStyle = randomColor();
ctx.fillText(getRandomNum(10), 150, getRandomNum(50));
}
getVerification();
</script>
</body>
</html>