UNPKG

svg_captcha_dxy

Version:

svg随机验证码

73 lines (68 loc) 2.67 kB
/** * 随机生成SVG验证码 * @returns Object * @param num {number} 定义生成的验证码的字符数量(默认4) 4~6 * @param color {boolean} 验证码的字符是否有背景色 true/false * @param noise {number} 图形验证码中的干扰线条数量(默认3) 2~5 */ function create({ num,color,noise }) { // 判断验证码数量 if (!num) num = 4; let str = "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM"; let data = `<svg xmlns="http://www.w3.org/2000/svg" version="1.1"><path d="M ${30*num} 0 L ${30*num} 50 M 0 0 L ${30*num} 0 M 0 0 L 0 50 M 0 50 L ${30*num} 50" stroke="#CCC" />` let text = '' // 判断是否加背景 if(color) { data += `<rect width="${30*num}" height="50" fill="slategrey" stroke="green" stroke-width="3"/>` } // 判断干扰线数量 if(!noise) noise = 3; // 生成验证码数量 for (var j = 0; j < num; j++) { // 随机字母数字 let numText = Math.floor(Math.random() * (str.length - 1 - 0 + 1) + 0) // 纵向随机高度 let tempHeight = Math.floor(Math.random() * (28 - 24 + 1) + 24) // 随机大小 let tempFontSize = Math.floor(Math.random() * (24 - 20 + 1) + 20) // 随机旋转 let tempRotate = Math.floor(Math.random() * (60 + 1)) * Math.floor(Math.random() * 3 - 1) let temp = 24 * ( j + 1 ) if(j === 0) temp = 18; let textHtml = `<text x="0" y="0" font-size="${tempFontSize}" transform="translate(${temp},${tempHeight})rotate(${tempRotate})" fill="${randomColor()}">${str[numText]}</text>`; data += textHtml; text += str[numText]; } // 生成干扰线 for (var i = 0; i< noise;i++) { let y1 = Math.floor(Math.random() * (40 + 1)+5); let y2 = Math.floor(Math.random() * (40 + 1)+5); let width = Math.floor(Math.random() * 2) + 1; let lineNoise = `<line x1 = "0" y1 = "${y1}" x2 = "120" y2 = "${y2}" stroke = "${randomColor()}" stroke-width = "${width}" > </line>` data += lineNoise; } return { text, data, } } /** * 随机获取一个十六进制颜色 * @date 2022-04-12 * @returns {any} 随机十六进制颜色字符串 */ function randomColor() { var color = ['#', ]; arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f"] for (var i = 0; i < 6; i++) { var index = Math.round(Math.random() * arr.length) color.push(arr[index]) } var str = color.join(""); return str; } module.exports = { create, }