/*** 图片验证码***/ @Component export default struct RandomTxtCanvas {@Link imgRandomTxt:string//图片验证private settings: RenderingContextSettings = new RenderingContextSettings(true)private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(200,200, this.settings)aboutToAppear(){this.imgRandomTxt=this.generateRandomCode(4) } //随机码generateRandomCode(length) {var result = '';var characters = 'ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijklmnpqrstuvwxyz123456789';var charactersLength = characters.length;for (var i = 0; i < length; i++) {result += characters.charAt(Math.floor(Math.random() * charactersLength));}return result;}//绘制图片getImage(){console.info(`validate:${this.imgRandomTxt}` )let colors=['#ed7272','#d9c529','#38649d','#000']let arr=this.imgRandomTxt.split('')for(var i=0;i<arr.length;i++) {let xMargin=this.getRandomNumber(1,10);let y=this.getRandomNumber(18,38);let x=xMargin+i*25+10this.offContext.font = `${this.getRandomNumber(50,70)}px sans-serif`this.offContext.fillText(arr[i], x,y,60)this.offContext.fillStyle=colors[this.getRandomNumber(0,3)]}this.offContext.lineWidth = 1this.offContext.moveTo(this.getRandomNumber(20, 40),this.getRandomNumber(20, 40))this.offContext.lineTo(120,this.getRandomNumber(5,40))this.offContext.moveTo(this.getRandomNumber(50, 110), this.getRandomNumber(5,40))let y=this.getRandomNumber(0, 40);this.offContext.bezierCurveTo(0, y, 200, 100, y, 200)this.offContext.moveTo(this.getRandomNumber(0, 30),this.getRandomNumber(0, 20))this.offContext.lineTo(this.getRandomNumber(80,120),this.getRandomNumber(10,40))this.offContext.lineJoin = 'miter'this.offContext.strokeStyle = '#ed7272'this.offContext.moveTo(this.getRandomNumber(0, 40),10)this.offContext.lineTo(this.getRandomNumber(50, 110), 60)this.offContext.lineTo(this.getRandomNumber(50, 110), 30)this.offContext.stroke()var image = this.offContext.transferToImageBitmap()this.context.transferFromImageBitmap(image)} //清空画布clearCanvas(){this.offContext.clearRect(0,0,500,500)this.offContext = new OffscreenCanvasRenderingContext2D(200,200, this.settings)this.context.clearRect(0,0,500,500)} //随机数getRandomNumber(min, max) {return Math.floor(Math.random() * (max - min + 1)) + min;}build() {Column() {Canvas(this.context).width(120).height('40').backgroundColor('#fff').onReady(() =>{this.getImage()}).onClick(()=>{this.clearCanvas()this.imgRandomTxt=this.generateRandomCode(4)this.getImage()})}} }
使用
//import RandomTxtCanvas from ''引用组件
@State imgRandomTxt:string=''
RandomTxtCanvas({imgRandomTxt:$imgRandomTxt})