canvas绘制验证码
在几乎每个网站登陆都会使用验证码来防止机器等非人操作,防止数据库被轻而易举的攻破。
验证码一般是PHP或java等生成的图片。在前端,用canva或SVG也可以绘制验证码;
以下是用canvas生成验证码的方法
我将该方法简单的封装成了Verify类,只需要传入canvas元素的类名或者id,就能初始化canvas
- html结构如下
<canvas id="canvas" width="120" height="40">
你的浏览器也太歪了
</canvas>
- js结构如下
class Verify{
constructor({el, width, height, len, lines, dots }){
//参数分别为canvas 元素, 绘制区域宽高, 验证字符个数 ,干扰线数量,干扰点数量
this.el = document.querySelector(el)
this.width = width || this.el.offsetWidth;
this.height = height || this.el.offsetHeight;
this.len = len || Math.floor(this.el.offsetWidth / 30)