@Component export default struct ImageCode { //用来配置CanvasRenderingContext2D对象的参数,包括是否开启抗锯齿,true表明开启抗锯齿。 private settings: RenderingContextSettings = new RenderingContextSettings(true) //用来创建CanvasRenderingContext2D对象,通过在canvas中调用CanvasRenderingContext2D对象来绘制。 private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) //指定canvas要绘制的图形的宽(可使用@Prop装饰器装饰,由调用此组件的父组件传递) @State canvas_width: number = 100; //指定canvas要绘制的图形的高 @State canvas_height: number = 40; //用于接收图形验证码的文本值 @State showCode: string = '' sCode: string = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,P,Q,R,S,T,U,V,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,p,q,r,s,t,u,v,w,x,y,z,1,2,3,4,5,6,7,8,9"; aCode: string[] = this.sCode.split(","); aLength: number = this.aCode.length; build() { Row() { //在canvas中调用CanvasRenderingContext2D对象。 Canvas(this.context) .width(this.canvas_width) .height(this.canvas_height) .backgroundColor('#CCC') .onReady(() => { //在这里绘制图形 this.showCode = this.drawImgCode(this.context,this.canvas_width,this.canvas_height) console.log(this.showCode) }) .onClick(() => { this.showCode = this.drawImgCode(this.context,this.canvas_width,this.canvas_height) console.log(this.showCode) }) } .width('100%') .height('100%') } drawImgCode(context: CanvasRenderingContext2D, canvas_width: number = 100, canvas_height: number = 40): string { //用于保存验证码 let showCode: string = '' //清楚当前画布内容,用作刷新画布 context.clearRect(0, 0, canvas_width, canvas_height) for (let i = 0; i < 4; i++) { //这里的for循环可以控制验证码位数 const j = Math.floor(Math.random() * this.aLength); //获取到随机的索引值 const deg = Math.random() - 0.5; //产生一个随机弧度 const txt = this.aCode[j]; //得到随机的一个内容 showCode += txt.toLowerCase(); //转小写 const x = 10 + i * 20; //文字在canvas上的x坐标 const y = canvas_height / 2 + Math.random() * 8; //文字在canvas上的y坐标 context.font = "20vp sans-serif"; context.translate(x, y); context.rotate(deg); context.fillStyle = this.getColor(); context.fillText(txt, 0, 0); context.rotate(-deg); context.translate(-x, -y); } for (let i = 0; i <= 5; i++) { //验证码上显示线条 context.strokeStyle = this.getColor(); context.beginPath(); context.moveTo(Math.random() * canvas_width, Math.random() * canvas_height); context.lineTo(Math.random() * canvas_width, Math.random() * canvas_height); context.stroke(); } for (let i = 0; i <= 20; i++) { //验证码上的小点 context.strokeStyle = this.getColor(); //随机生成 context.beginPath(); const x = Math.random() * canvas_width; const y = Math.random() * canvas_height; context.moveTo(x, y); context.lineTo(x + 1, y + 1); context.stroke(); } return showCode } getColor() { const r = Math.floor(Math.random() * 256); const g = Math.floor(Math.random() * 256); const b = Math.floor(Math.random() * 256); return "rgb(" + r + "," + g + "," + b + ")"; } }
import ImageCode from './components/ImageCode' @Entry @Component struct Index { build() { Row() { TextInput({placeholder:'请输入验证码'}) .layoutWeight(1) ImageCode() .width(100) .height(40) } .height('100%') .width('100%') } }