canvas驗證碼 uni-app/小程序

效果圖 

 

效果圖

話很少說,直接上代碼


js

methods: {css

draw(show_num) {canvas

const ctx = uni.createCanvasContext('myCanvas');dom

ctx.setFillStyle('#fefefe')字體

ctx.fillRect(0,0,110,40)this

for (var i = 0; i < 8; i++) {spa

var x = Math.floor(Math.random() * 110);blog

var y = Math.floor(Math.random() * 40);it

var x1 = Math.floor(Math.random() * 110);console

var y1 = Math.floor(Math.random() * 40);class

console.log('--x--' + x, '--y--' + y);

console.log('--x1--' + x1, '--y1--' + y1);

ctx.beginPath();

ctx.setStrokeStyle(this.randomColor());

ctx.setLineWidth(1);

ctx.moveTo(x1, y1);

ctx.lineTo(x, y);

ctx.stroke();

}

ctx.setFontSize(24);

var arr = show_num.split('');

var tx = 0;

arr.forEach((e, i) => {

tx += 20;

var ty = Math.floor((Math.random()*4) + 24);

ctx.setFillStyle(this.randomColor());

if (e) {

console.log('字體加粗1');

ctx.fillText(e, tx, ty - 0.5);

ctx.fillText(e, tx - 0.5, ty);

}

ctx.fillText(e, tx, ty);

if (e) {

console.log('字體加粗2');

ctx.fillText(e, tx, ty + 0.5);

ctx.fillText(e, tx + 0.5, ty);

}

ctx.rotate((0.4-Math.random()) * 0.15);

});

ctx.draw();

},

//獲得隨機的顏色值

randomColor() {

var r = Math.floor(Math.random() * 256);

var g = Math.floor(Math.random() * 256);

var b = Math.floor(Math.random() * 256);

return 'rgb(' + r + ',' + g + ',' + b + ')';

},

onCanvas() {

console.log('onCanvas');

var show_num = 'fdgt';

this.draw(show_num);

},

},

mounted() {

var show_num = 'fdgt';

this.draw(show_num);

},

view

<canvas class="canvas" canvas-id="myCanvas" @click="onCanvas"></canvas>

css

.canvas {

width: 110px;

height: 40px;

border: 1px solid #e5e5e5;

}

相關文章
相關標籤/搜索