本文轉載自【微信公眾號:趣談前端,ID:beautifulFront】經微信公眾號授權轉載,如需轉載與原文作者聯繫
本文主要介紹用canvas實現圖形驗證碼的一些思路以及如何用javascript面向對象的方式更友好的實現canvas的功能,關於canvas的一些基本使用方法和API我整理了一個思維導圖,大家感興趣的可以參考學習。
你將收穫
閉包的使用canvas常用api的使用javascript面向對象的實現方式實現一個canvas的圖形驗證碼的一般思路和常用算法設計思路
用canvas生成畫布用canvas畫幹擾線或躁點生成隨機不重複的n的字母用canvas繪製文字初始化和canvas點擊事件組件化封裝文末將附上組件封裝的源碼,歡迎大家隨時溝通交流。關於項目的打包,我將使用自己基於gulp4搭建的9012教你如何使用gulp4開發項目腳手架。
效果預覽
實現思路
我將按照上文中的設計思路的步驟一步步實現,首先我們先定義一個es5類:
function Gcode(el, option) {
this.el = typeof el === 'string' ? document.querySelector(el) : el;
this.option = option;
this.init();
}
其中init是用來初始化用的,參數el代表需要掛載的元素或元素id,option為傳入的可選項,稍後會在代碼中體現,通常這也是面向對象的常用套路。
繪製畫布
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;
}
}
}
這裡我們在初始化方法中先定義一個canvas畫布,寬高為用戶自定義的寬高,默認為200*40。
繪製幹擾線
// 畫幹擾線
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();
}
}
這裡我們對類Gcode定義原型方法drawLine,然後通過for循環繪製隨機位置的線條,為了讓canvas每次點擊能清空之前的幹擾線,我們使用clearRect來清除畫布。
生成隨機不重複的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
}
}
// 生成指定個數的隨機文字
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來實現生成唯一不重複的n個隨機字符。當然筆者認為這個方法並不優雅,你也可以使用uuid的方式或者更好的方式,歡迎隨時和筆者交流。
用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);
}
},
這裡和上文畫線實現類似。就不做過多介紹了。
初始化和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
})
})();