原生 js 图形验证码代码
HTML 代码:
<canvas id="yzm" width="150" height="50"></canvas> <a href="javascript:;" id="a1">看不清,换一个</a>
CSS 代码:
#yzm { border:1px solid #009900; background:url(https://media.mybj123.com/wp-content/uploads/2021/11/1636593980-eccbc87e4b5ce2f.png) }
JS 代码:
window.addEventListener("DOMContentLoaded", function() { var a1 = document.getElementById("a1"); var yzm = document.getElementById("yzm"); var cxt = yzm.getContext("2d"); function showYzm() { cxt.clearRect(0, 0, 150, 50); //清空画布区域 var str = "012345678910ABCDEFGHIJKLMNOPQRSTUVWXYZ"; var validate = ""; var position = 0; var x, y; var fontSize = 30; cxt.beginPath(); cxt.fillStyle = "#aaaaaa"; for (var i = 0; i < 4; i++) { x = 20 + (i * 30); y = 25 + Math.ceil(Math.random() * 20); fontSize = 10 + Math.ceil(Math.random() * 20); cxt.font = "bold " + fontSize + "px Arial"; position = Math.ceil(Math.random() * 1000) % 36; cxt.fillText(str.substr(position, 1), x, y, 300); } } showYzm(); a1.addEventListener("click", function() { showYzm(); }); });