html5如何实验验证码,利⽤HTML5实现Canvas验证码代码特效描述:利⽤HTML5实现 Canvas 验证码代码。利⽤HTML5实现Canvas验证码代码
代码结构
1. 引⼊JS
2. HTML代码
var nums = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z'];
drawCode();
// 绘制验证码
function drawCode() {
var canvas = ElementById("verifyCanvas"); //获取HTML端画布
var context = Context("2d"); //获取画布2D上下⽂
context.fillStyle = "cornflowerblue"; //画布填充⾊
context.fillRect(0, 0, canvas.width, canvas.height); //清空画布
context.fillStyle = "white"; //设置字体颜⾊
context.font = "25px Arial"; //设置字体
var rand = new Array();
var x = new Array();
var y = new Array();
for (var i = 0; i < 5; i++) {
rand[i] = nums[Math.floor(Math.random() * nums.length)]
x[i] = i * 16 + 10;
y[i] = Math.random() * 20 + 20;
context.fillText(rand[i], x[i], y[i]);
}
//画3条随机线
for (var i = 0; i < 3; i++) {
drawline(canvas, context);
}
// 画30个随机点
for (var i = 0; i < 30; i++) {
drawDot(canvas, context);
}
实现特效的代码jsconvertCanvasToImage(canvas)
}
// 随机线
function drawline(canvas, context) {
context.lineTo(Math.floor(Math.random() * canvas.width), Math.floor(Math.random() * canvas.height)); //随机线的终点x坐标是画布宽度,y坐标是画布⾼度的随机数
context.lineWidth = 0.5; //随机线宽
context.strokeStyle = 'rgba(50,50,50,0.3)'; //随机线描边属性
context.stroke(); //描边,即起点描到终点
}
// 随机点(所谓画点其实就是画1px像素的线,⽅法不再赘述)
function drawDot(canvas, context) {
var px = Math.floor(Math.random() * canvas.width);
var py = Math.floor(Math.random() * canvas.height);
context.lineTo(px + 1, py + 1);
context.lineWidth = 0.2;
context.stroke();
}
/
/ 绘制图⽚
function convertCanvasToImage(canvas) {
var image = ElementById("code_img");
image.src = DataURL("image/png");
return image;
}
// 点击图⽚刷新
$('#verifyCanvas').remove();
$('#verify').after('')
drawCode();
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论