Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement a graphic CAPTCHA for getting started with Canvas

2025-01-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "how to achieve a graphic CAPTCHA in Canvas entry practice". In daily operation, I believe many people have doubts about how to achieve a graphic CAPTCHA in Canvas entry practice. Xiaobian consulted all kinds of data and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the doubt of "how to achieve a graphic CAPTCHA in Canvas entry practice". Next, please follow the editor to study!

You will reap

Use of closures

The use of api commonly used in canvas

Object-oriented implementation of javascript

General ideas and algorithms for implementing a canvas graphic CAPTCHA

Design ideas

Use canvas to generate canvas

Use canvas to draw interference lines or restless points

Generate random n letters that are not repeated

Draw text with canvas

Initialization and canvas click events

Component-based packaging

The source code of the component package will be attached at the end of the article. You are welcome to communicate at any time. With regard to project packaging, I will use my own gulp4-based 9012 to teach you how to use gulp4 development project scaffolding.

Effect preview

Realization idea

I will follow the design ideas above step by step. First, let's define an es5 class:

Function Gcode (el, option) {this.el = typeof el = = 'string'? Document.querySelector (el): el; this.option = option; this.init ();}

The init is used for initialization, and the parameter el represents the element to be mounted or the element id,option is optional, which will be reflected in the code later, which is usually a common pattern for object-oriented.

1. Draw a canvas

Gcode.prototype = {constructor: Gcode, init: function () {if (this.el.getContext) {isSupportCanvas = true; var ctx = this.el.getContext ('2d'), / / set canvas width and height cw = this.el.width = this.option.width | | 200, ch = this.el.height = this.option.height | | 40 }

Here, in the initialization method, we first define a canvas canvas with a user-defined width and height. The default is 200x40.

two。 Draw interference lines

/ / draw interference line drawLine: function (ctx, lineNum, maxW, maxH) {ctx.clearRect (0,0, maxW, maxH); for (var iTuno; I

< lineNum; i++) { var dx1 = Math.random()* maxW, dy1 = Math.random()* maxH, dx2 = Math.random()* maxW, dy2 = Math.random()* maxH; ctx.strokeStyle = 'rgb(' + 255*Math.random() + ',' + 255*Math.random() + ',' + 255*Math.random() + ')'; ctx.beginPath(); ctx.moveTo(dx1, dy1); ctx.lineTo(dx2, dy2); ctx.stroke(); } } 这里我们对类Gcode定义原型方法drawLine,然后通过for循环绘制随机位置的线条,为了让canvas每次点击能清空之前的干扰线,我们使用clearRect来清除画布。 3.生成随机不重复的n个字符 我们通过递归实现,如下==: // 生成唯一文字 generateUniqueText: function(source, hasList, limit) { var text = source[Math.floor(Math.random()*limit)]; if(hasList.indexOf(text) >

-1) {return this.generateUniqueText (source, hasList, limit)} else {return text}} / / generate a specified number of random words randomText: function (len) {var source = ['a', 'baked,' caged, 'dashed,' eyed, 'faded,' gashed, 'hacked,' ified, 'jacked,' kicking,'l' 'masked,' oiled, 'paired,' qpressed, 'rusted,' sworn, 'tweeted,' upright, 'vested,' wicked, 'xylene,' yearly,'z'] Var result = []; var sourceLen = source.length; for (var item0; I

< len; i++) { var text = this.generateUniqueText(source, result, sourceLen); result.push(text) } return result.join('') } 我们通过定义一个字母表,传入生成的随机字母的个数,配合generateUniqueText来实现生成唯一不重复的n个随机字符。当然笔者认为这个方法并不优雅,你也可以使用uuid的方式或者更好的方式,欢迎随时和笔者交流。 4.用canvas绘制文字 // 画文字 drawText: function(ctx, text, maxH) { var len = text.length; for(var i=0; i < len; i++) { var dx = 30 * Math.random() + 30* i, dy = Math.random()* 5 + maxH/2; ctx.fillStyle = 'rgb(' + 255*Math.random() + ',' + 255*Math.random() + ',' + 255*Math.random() + ')'; ctx.font = '30px Helvetica'; ctx.textBaseline = 'middle'; ctx.fillText(text[i], dx, dy); } }, 这里和上文画线实现类似。就不做过多介绍了。 5.初始化和canvas点击事件 接下来我们看看完整的初始化代码: init: function() { if(this.el.getContext) { isSupportCanvas = true; var ctx = this.el.getContext('2d'), // 设置画布宽高 cw = this.el.width = this.option.width || 200, ch = this.el.height = this.option.height || 40, textLen = this.option.textLen || 4, lineNum = this.option.lineNum || 4; var text = this.randomText(textLen); this.onClick(ctx, textLen, lineNum, cw, ch); this.drawLine(ctx, lineNum, cw, ch); this.drawText(ctx, text, ch); } } 点击事件主要是为了用户点击可以切换验证码: onClick: function(ctx, textLen, lineNum, cw, ch) { var _ = this; this.el.addEventListener('click', function(){ text = _.randomText(textLen); _.drawLine(ctx, lineNum, cw, ch); _.drawText(ctx, text, ch); }, false) } 到此,一个完整的验证码组件实现完成,怎么用呢?如下: new Gcode('#canvas_code', { lineNum: 6, // 可选 textLen: 4, // 可选 width: 200, // 可选 height: 50 // 可选 }) 完整代码如下,欢迎学习交流: // canvas绘制图形验证码 (function(){ function Gcode(el, option) { this.el = typeof el === 'string' ? document.querySelector(el) : el; this.option = option; this.init(); } Gcode.prototype = { constructor: Gcode, init: function() { if(this.el.getContext) { isSupportCanvas = true; var ctx = this.el.getContext('2d'), // 设置画布宽高 cw = this.el.width = this.option.width || 200, ch = this.el.height = this.option.height || 40, textLen = this.option.textLen || 4, lineNum = this.option.lineNum || 4; var text = this.randomText(textLen); this.onClick(ctx, textLen, lineNum, cw, ch); this.drawLine(ctx, lineNum, cw, ch); this.drawText(ctx, text, ch); } }, onClick: function(ctx, textLen, lineNum, cw, ch) { var _ = this; this.el.addEventListener('click', function(){ text = _.randomText(textLen); _.drawLine(ctx, lineNum, cw, ch); _.drawText(ctx, text, ch); }, false) }, // 画干扰线 drawLine: function(ctx, lineNum, maxW, maxH) { ctx.clearRect(0, 0, maxW, maxH); for(var i=0; i < lineNum; i++) { var dx1 = Math.random()* maxW, dy1 = Math.random()* maxH, dx2 = Math.random()* maxW, dy2 = Math.random()* maxH; ctx.strokeStyle = 'rgb(' + 255*Math.random() + ',' + 255*Math.random() + ',' + 255*Math.random() + ')'; ctx.beginPath(); ctx.moveTo(dx1, dy1); ctx.lineTo(dx2, dy2); ctx.stroke(); } }, // 画文字 drawText: function(ctx, text, maxH) { var len = text.length; for(var i=0; i < len; i++) { var dx = 30 * Math.random() + 30* i, dy = Math.random()* 5 + maxH/2; ctx.fillStyle = 'rgb(' + 255*Math.random() + ',' + 255*Math.random() + ',' + 255*Math.random() + ')'; ctx.font = '30px Helvetica'; ctx.textBaseline = 'middle'; ctx.fillText(text[i], dx, dy); } }, // 生成指定个数的随机文字 randomText: function(len) { var source = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']; var result = []; var sourceLen = source.length; for(var i=0; i< len; i++) { var text = this.generateUniqueText(source, result, sourceLen); result.push(text) } return result.join('') }, // 生成唯一文字 generateUniqueText: function(source, hasList, limit) { var text = source[Math.floor(Math.random()*limit)]; if(hasList.indexOf(text) >

-1) {return this.generateUniqueText (source, hasList, limit)} else {return text} new Gcode ('# canvas_code', {lineNum: 6})} () At this point, on the "Canvas entry how to achieve a graphic CAPTCHA" study is over, I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report