<!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>Document</title>
<style>
.yzm{
background-color: rgb(26, 224, 53);
border-radius: 5px;
cursor: pointer;
display: block;
margin: 100px auto;
}
</style>
</head>
<body>
<!-- 画布标签,宽高在这里设定 -->
<canvas class="yzm" width="110px" height="50px"></canvas>
<script>
window.addEventListener("DOMContentLoaded", function () {
// 获取节点
const yzm = document.querySelector(".yzm")
// 画布绘制文字
const cxt = yzm.getContext("2d");
function showYzm() {
// 每次生成新的随机码,都要清空上一次的随机码
cxt.clearRect(0, 0, 150, 50); //清空画布区域
// 随机码字符串
let str = "012345678910ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// 定义下边需要用到的变量
let position = 0;
let x, y;
let fontSize = 30;
// 开启路径
cxt.beginPath();
// 路径填充样式
cxt.fillStyle = "#ccc";
for (let i = 0; i < 4; i++) {
x = 20 + (i * 20);//生成四个X坐标
y = 25 + Math.floor(Math.random() * 20);//生成四个y坐标
fontSize = 10 + Math.floor(Math.random() * 20);//字号
cxt.font = "bold " + fontSize + "px Arial";//字体属性
position = Math.floor(Math.random() * 35);//在36个字母和数字中随机生成一个索引值(运行了四次)
cxt.fillText(str.substr(position, 1), x, y, 300);//通过substr截取4个str中的元素(position为随机变量所以截取数字随机)
}
}
// 页面加载完成调用一次
showYzm();
// 每次点击再次调用
yzm.addEventListener("click", function () {
showYzm();
});
});
</script>
</body>
</html>
js 随机生成验证码
最新推荐文章于 2023-09-17 18:45:59 发布