console
var cas=document.querySelector('#canvas');
var ctx=cas.getContext('2d');
function randomCode(position,needDisturbPoint,needDisturbLine){
function randNum(min,max){
return Math.floor(Math.random()*(max-min+1)+min);
}
function randColor(min,max){
var r = randNum(min,max);
var g = randNum(min,max);
var b = randNum(min,max);
return 'rgb('+r+','+g+','+b+')';
}
function drawRect(x,y,w,h){
ctx.fillStyle=randColor(170,250);
ctx.fillRect(x,y,w,h);
}
function get4RandomCode(){
var code = "";
var data='qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890';
for(var i=0;i<120;i+=30){
var c=data[randNum(0,data.length-1)];
code = code + c;
ctx.fillStyle=randColor(60,160);
ctx.font=randNum(15,40)+'px SimHei';
ctx.fillText(c,i+randNum(5,12),randNum(15,30));
}
return code.toUpperCase();
}
function getDisturbLine(){
for (var i=0;i<10;i++) {
ctx.beginPath();
ctx.moveTo(randNum(0,120),randNum(0,120));
ctx.lineTo(randNum(0,120),randNum(0,120));
ctx.strokeStyle=randColor(60,160);
ctx.stroke();
}
}
function getDisturbPoint(){
ctx.beginPath();
ctx.arc(randNum(0,120),randNum(0,30),randNum(1,5),0,2*Math.PI);
ctx.strokeStyle=randColor(60,160);
ctx.stroke();
ctx.fill();
}
drawRect(position.x,position.y,position.w,position.h);
var code = get4RandomCode();
randColor(0,255);
if(needDisturbLine) getDisturbLine();
if(needDisturbPoint) getDisturbPoint();
return code;
}
let code = randomCode({x:0,y:0,w:120,h:30},true,true);
console.log(code);
<canvas id="canvas" width="120" height="30" style="cursor: pointer;"></canvas>