canvas渐变色圆环进度条,angular2

//canvas.component.html
<div class="container">
  <canvas #voucherCanvas width="100%" height="100%"></canvas>
</div>
//自定义模板数据 canvas.component.ts
import { Component, OnInit, ViewChild, ElementRef, Input } from '@angular/core';

@Component({
  selector: 'app-canvas',
  templateUrl: './canvas.component.html',
  styleUrls: ['./canvas.component.scss']
})
export class BusinessCanvasComponent implements OnInit {
  @ViewChild('voucherCanvas')
  voucherCanvas: ElementRef;

  constructor(
    public element: ElementRef
  ) { }

  ngOnInit() {
    //自定义模板数据
    this.voucher: any = {
        totalDta: 800,
        currentDta: 100,
    };
    /**
    *  arc(x, y, radius, startAngle, endAngle, anticlockwise)
    *  画一个以(x,y)为圆心的以radius为半径的圆弧(圆),从startAngle开始到endAngle结束,按照anticlockwise给定的方向(默认为顺时针true/false)来生成。
    */
    this.drawCanvanPercent(this.voucher);
  }

  drawCanvanPercent(voucher): void {
    const canvas = this.voucherCanvas.nativeElement;
    if (canvas.getContext) {
      const ctx: any = canvas.getContext('2d');
      // 画笔设置
      ctx.strokeStyle = "#E7F3FE";
      ctx.lineWidth = '10'; 
      ctx.lineCap = 'round';
      // 灰色圆环
      ctx.beginPath();
      ctx.arc(50, 50, 40, (Math.PI / 180) * 0, (Math.PI / 180) * 360, false);
      ctx.stroke();
      ctx.closePath();
      // 红色比例圆环
      const text = Math.round((voucher.currentDta / voucher.totalDta) * Math.pow(10, 4)) / Math.pow(10, 4) * 100; //圆环内部展示进度值
      this.drawArc(this.voucher, ctx, text);
    } else {
      console.log('此浏览器不支持展示canvas');
    }
  }

  // 根据角度比例画圆弧
  drawArc(voucher, ctx, text) {
    const startAngle = -90;
    const endAngle = (voucher.currentDta / voucher.totalDta) * 360 - 90;
    ctx.beginPath();
    ctx.arc(50, 50, 40, (Math.PI / 180) * startAngle, (Math.PI / 180) * endAngle, flase);
    // color
/*
*createLinearGradient(x1, y1, x2, y2)
*createLinearGradient 方法接受 4 个参数,表示渐变的起点 (x1,y1) 与终点 (x2,y2)。
*/ const g = ctx.createLinearGradient(50, 10, 50, 90); g.addColorStop(0, '#F76B1C'); //开始颜色 g.addColorStop(1, '#FAD760'); //结束颜色 ctx.strokeStyle = g; ctx.stroke(); ctx.closePath(); // tag 给进度值拼接上% text = `${text}` + '%'; const myText = ctx.measureText(text); ctx.font = '14px DINOT-Medium '; ctx.fillStyle = 'rgba(0,0,0,0.25)'; ctx.fillText(text, (this.voucher.width - myText.width) / 2 - 5, this.voucher.height / 2 + 5); } }
//主页面
<app-canvas></app-canvas>