效果圖?
話不多說(shuō),直接上代碼
js
methods: {
draw(show_num) {
const ctx = uni.createCanvasContext('myCanvas');
ctx.setFillStyle('#fefefe')
ctx.fillRect(0,0,110,40)
for (var i = 0; i < 8; i++) {
var x = Math.floor(Math.random() * 110);
var y = Math.floor(Math.random() * 40);
var x1 = Math.floor(Math.random() * 110);
var y1 = Math.floor(Math.random() * 40);
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();
},
//得到隨機(jī)的顏色值
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;
}