在 Angular 中创建圆环图 2

Create a Donut chart in Angular 2

我在 SVG 方面的技能非常有限,Canvas 和 CSS3。我一直在尝试在 angular 2 中创建圆环图,但没有成功。有一些现成可用的库,但我们不允许将第 3 方库拉入 project.Can 有人指出我正确的方向或帮助我 it.Basically 我玩过 SVG 但似乎在 SVG

中没有 'arc' 元素

使用带有 stroke-dasharray 和 stroke-dashoffset 的 SVG 可以轻松完成此操作。在您的甜甜圈组件 html 中包含以下代码:-

  <svg height="100%" width="100%" viewBox="0 0 120 120">       
     <circle  *ngFor="let item of items;let i=index" cx="60" cy="60" r="50" fill="transparent" stroke-width="20"
     [attr.stroke-dasharray]="getPerimeter(50)" [attr.stroke-dashoffset]="getOffset(50,i)" [attr.stroke]="getColor(i)"/>             
  </svg>

基本上圆的周长由2πr决定,其中r是半径。笔画偏移量将指定新段 start.This 可以通过从总 perimeter.In 您的 TS 文件中减去先前段占用的周长百分比来计算:-

export class DonutComponent{

 items:Array<{name:string,count:number,color:string}>=[
    {name:'Orange',count:50,color:'orange'},
    {name:'Apple',count:25,color:'red'},
    {name:'Pear',count:15,color:'green'}
  ];
 private _total:number =0;
 constructor() {
   if(this.items.length>0)
   {
     this._total = this.items.map(a=>a.count).reduce((x,y)=>x+y);
   }

 }

  getPerimeter(radius:number):number
  {
    return Math.PI*2*radius;
  }

  getColor(index:number):string
  {
    return this.items[index].color;
  }

  getOffset(radius:number,index:number):number
  {   
    var percent=0;
    for(var i=0;i<index;i++)
    {
      percent+=((this.items[i].count)/this._total);
    }
    var perimeter = Math.PI*2*radius;
    return perimeter*percent;
  }
}

如果要使甜甜圈通用,可以将这些项目作为组件的输入

github 中添加了更通用的源代码。