1、创建dom元素
<canvas id="authCode"></canvas>2、定义canvas参数
let options={ canvasId:"authCode", txt:"ZHTH", height:32, width:64, }3、调用方法画图
this.writeAuthCode(options);writeAuthCode(options){ var canvas = document.getElementById("authCode") if(canvas){ canvas.width = options.width || 300 canvas.height = options.height || 150 let ctx = canvas.getContext('2d') //创建一个canvas对象 ctx.textBaseline = "middle" ctx.fillStyle = this.randomColor(180,255) ctx.fillRect(0,0,options.width,options.height) for(var i=0 ;i < options.txt.length;i++){ var tex = options.txt.charAt(i) //让每个字都不一样 ctx.font = "20px SimHei" ctx.fillStyle = this.randomColor(50,160) //随机生成字体颜色 ctx.shadowOffsetY = this.randomNum(-3,3) ctx.shadowBlur = this.randomNum(-3,3) ctx.shadowColor = "rgba(0,0,0,0.3)" var x = options.width / (options.txt.length+1)*(i+1) var y = options.height / 2 var deg = this.randomNum(-3,3) // 设置旋转角度和坐标原点 ctx.translate(x,y) ctx.rotate(deg * Math.PI / 180) ctx.fillText(options.txt,0,0) // 恢复旋转角度和坐标原点 // ctx.rotate(-deg * Math.PI / 180) // ctx.translate(-x,-y) } } } //随机颜色 randomColor=(min,max)=>{ let r = this.randomNum(min,max) let g = this.randomNum(min,max) let b = this.randomNum(min,max) return `rgb(${r},${g},${b})`; } //随机数字 randomNum=(min,max)=>{ return Math.floor(Math.random()*(max-min)+min) }