samhuilong |
2020-06-02 20:30 |
我用typescript写的web版本电池控件的代码,来向原版致敬。
update(): void { let context: CanvasRenderingContext2D = this.context; let width: number = this.canvasWidth; let height: number = this.canvasHeight; context.clearRect(0, 0, width, height); context.save(); //绘制边框 this.drawBorder(context); //绘制背景 this.drawBg(context); //绘制头部 this.drawHead(context); context.restore(); } protected drawBorder(context: CanvasRenderingContext2D): void { context.save(); let width: number = this.canvasWidth; let height: number = this.canvasHeight; let headWidth: number = width / 10; let batteryWidth: number = width - headWidth; //绘制电池边框 let topLeft: Point = new Point(5, 5); let bottomRight: Point = new Point(batteryWidth, height - 5); this.batteryRect = new Rect(topLeft, bottomRight); context.strokeStyle = this.borderColorStart.name; context.lineWidth = 5; let painter = new Painter(context); painter.drawRoundedRect(this.batteryRect.left, this.batteryRect.top, this.batteryRect.width, this.batteryRect.height, this.borderRadius, DrawMode.Stroke); context.restore(); } protected drawBg(context: CanvasRenderingContext2D): void { context.save(); let batteryGradient: CanvasGradient = context.createLinearGradient(0, 0, 0, this.canvasHeight); if (this.currentValue <= this.alarmValue) { batteryGradient.addColorStop(0.0, this.alarmColorStart.name); batteryGradient.addColorStop(1.0, this.alarmColorEnd.name); } else { batteryGradient.addColorStop(0.0, this.normalColorStart.name); batteryGradient.addColorStop(1.0, this.normalColorEnd.name); } context.fillStyle = batteryGradient; let margin: number = Math.min(this.canvasWidth, this.canvasHeight) / 20; let unit: number = (this.batteryRect.width - (margin * 2)) / 100; let width: number = this.currentValue * unit; let topLeft: Point = new Point(this.batteryRect.left + margin, this.batteryRect.top + margin); let bottomRight: Point = new Point(width + margin + 5, this.batteryRect.bottom - margin); let rect = new Rect(topLeft, bottomRight); let painter = new Painter(context); painter.drawRoundedRect(rect.left, rect.top, rect.width, rect.height, this.bgRadius, DrawMode.Fill); context.restore(); } protected drawHead(context: CanvasRenderingContext2D): void { context.save(); let width: number = this.canvasWidth; let height: number = this.canvasHeight; let headRectTopLeft: Point = new Point(this.batteryRect.right, height / 3); let headRectBottomRight: Point = new Point(width, height - height / 3); let headRect: Rect = new Rect(headRectTopLeft, headRectBottomRight); let headRectGradient: CanvasGradient = context.createLinearGradient(headRect.left, headRect.top, 0, 0); headRectGradient.addColorStop(0.0, this.borderColorStart.name); headRectGradient.addColorStop(1.0, this.borderColorEnd.name); context.fillStyle = headRectGradient; let painter = new Painter(context); painter.drawRoundedRect(headRect.left, headRect.top, headRect.width, headRect.height, this.bgRadius, DrawMode.Fill); context.restore(); }
|
|