-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSpiderChart.min.js
More file actions
16 lines (16 loc) · 2.63 KB
/
Copy pathSpiderChart.min.js
File metadata and controls
16 lines (16 loc) · 2.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
'use strict'
class SpiderChart{_canvas;_ctx;_center;_points;_entities;_shrink=0;_offset=1.05;_options={'strikeColor':'lightgray','strikeWidth':1,'strikeOpacity':0.5,'params':['1','2','3','4','5']};constructor(canvasId,height,width){this._canvas=document.getElementById(canvasId);this._canvas.height=height;this._canvas.width=width;this._ctx=this._canvas.getContext('2d')}
setOffset(offset){this._offset=offset}
setGrid(color,width,opacity){this._options.strikeColor=color;this._options.strikeWidth=width;this._options.strikeOpacity=opacity}
setParams(params){this._options.params=params}
addEntity(data){if(undefined===data.id||undefined===data.data)
return!1;this._entities.push(data);return!0}
renderGraph(interval=5,size=null,recursive=!1){this._center.x=this._canvas.width/2;this._center.y=this._canvas.height/2;if(size===null)
size=this._center.x*0.9
if(this._shrink===0)
this._shrink=size/interval;let numberOfSides=5,step=2*Math.PI/numberOfSides,shift=(Math.PI/180.0)*-18;this._ctx.beginPath();for(let i=0;i<=numberOfSides;i++){let curStep=i*step+shift;let x=this._center.x+size*Math.cos(curStep);let y=this._center.y*this._offset+size*Math.sin(curStep);this._ctx.lineTo(x,y);if(!recursive&&i!=numberOfSides){this._ctx.fillText(this._options.params[i],x-10,y);this._points.push({'x':x,'y':y})}}
this._ctx.strokeStyle=this._options.strikeColor;this._ctx.lineWidth=this._options.strikeWidth;this._ctx.stroke();if(interval-1>0)
this.renderGraph(interval-1,size-this._shrink,!0)
else{this._shrink=0;this._points.forEach(point=>{this._ctx.beginPath();this._ctx.moveTo(this._center.x,this._center.y*this._offset);this._ctx.lineTo(point.x,point.y);this._ctx.strokeStyle=this._options.strikeColor;this._ctx.lineWidth=this._options.strikeWidth;this._ctx.stroke()});this.renderEntities()}}
renderEntities(){this._entities.forEach(entity=>{this._ctx.beginPath();this._points.forEach((point,idx)=>{let multi=entity.data[idx]/100;let vector=[(point.x-this._center.x)*multi,(point.y-this._center.y*this._offset)*multi];this._ctx.lineTo(this._center.x+vector[0],this._center.y*this._offset+vector[1]);this._ctx.strokeStyle=this._options.strikeColor;this._ctx.lineWidth=this._options.strikeWidth;this._ctx.stroke()});this._ctx.closePath();this._ctx.fillStyle=entity.color;this._ctx.fill()})}
renderLegend(){let bottom=this._canvas.height-10;this._entities.forEach((entity,idx)=>{this._ctx.fillStyle=entity.color;this._ctx.beginPath();this._ctx.arc(idx*50+5,bottom,5,0,2*Math.PI);this._ctx.stroke();this._ctx.fill();this._ctx.fillStyle="rgba(0, 0, 0, 1)";this._ctx.fillText(entity.id,idx*50+13,bottom+3)})}}