canvas底紋隨機驗證碼製作
阿新 • • 發佈:2018-11-13
一、HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#mycanvas{
border: 1px solid;
margin-top: 10px;
margin-left: 90px;
}
</style>
</head>
<body>
<form method="get" onsubmit="return yanzheng()"> 驗證碼:
<input type="text" name="num" id="yzm" />
<input type="submit" value="提交" onclick="return yanzheng()"/>
<br />
</form >
<canvas id="mycanvas" onclick="shengchengyzm()"></canvas>
<script type="text/javascript">
var hb;
window.onload=function(){
var mycanvas=document.getElementById("mycanvas");
mycanvas.width=100;
mycanvas.height=40 ;
hb=mycanvas.getContext("2d");
hb.fillStyle=getcolor();
hb.fillRect(0,0,100,40);
}
function shengchengyzm(){
hb.beginPath();
var ran=parseInt(Math.random()*10000)%900000+100000;
hb.font="20px 微軟雅黑";
hb.fillStyle=getcolor();
hb.fillText(ran,15,28);
//干擾線
for (var i = 0; i < 20; i++) {
hb.beginPath();
var w=parseInt(Math.random()*10000)%mycanvas.width;
var h=parseInt(Math.random()*10000)%mycanvas.height;
hb.moveTo(w,h);
w=parseInt(Math.random()*10000)%mycanvas.width;
h=parseInt(Math.random()*10000)%mycanvas.height;
hb.lineTo(w,h);
hb.strokeStyle=getcolor();
hb.stroke();
}
//干擾點
for (var i = 0; i <100; i++) {
hb.beginPath();
var w=parseInt(Math.random()*10000)%mycanvas.width;
var h=parseInt(Math.random()*10000)%mycanvas.height;
hb.moveTo(w,h);
hb.lineTo(w+1,h+1);
hb.strokeStyle=getcolor();
hb.stroke();
}
//蒙版
hb.beginPath();
hb.fillStyle="rgba(255,255,0,0.4)";
hb.fillRect(0,0,100,40);
};
function getcolor(){
var r=parseInt(Math.random()*10000)%256;
var g=parseInt(Math.random()*10000)%256;
var b=parseInt(Math.random()*10000)%256;
return "rgb("+r+","+g+","+b+")";
}
function yanzheng(){
return false;
}
</script>
</body>
</html>
二、效果圖