社区文档构建进行中,欢迎编辑。社区答疑群(非官方):717421103,点点小课堂(腾讯会议):5696651544

全站通知:

Widget:Pie

来自WIKI实验室WIKI_BWIKI_哔哩哔哩
跳到导航 跳到搜索

<script> function Pie(datas=[],size=300,blank=0){ this.canvas=document.createElement("canvas") this.brush=this.canvas.getContext("2d") this.datas=[] this.total=0 size=Number(size) if(isNaN(size)||size<0){ size=300 console.log("%c尺寸异常,已设置为300","color:red") } blank=Number(blank) if(isNaN(blank)||blank>size){ blank=0 console.log("%c中空异常,已设置为0","color:red") } this.size=size this.blank=blank this.addData(datas) } Pie.prototype.addData=function(datas){ let total=0 for(let i=0;i<datas.length;i++){ datas[i]=Number(datas[i]) if(isNaN(datas[i])||datas[i]<0){ throw new Error("数据中有错误") } total+=datas[i] } this.total+=total this.datas=this.datas.concat(datas) this.draw() } Pie.prototype.draw=function(){ this.canvas.width=this.size+this.brush.lineWidth this.canvas.height=this.size+this.brush.lineWidth this.brush.save() this.brush.beginPath this.brush.translate(this.canvas.width/2,this.canvas.height/2) for(let i=0;i<this.datas.length;i++){ this.brush.moveTo(0,0) this.brush.lineTo(this.size/2,0) this.brush.arc(0,0,this.size/2,0,this.datas[i]/this.total*2*Math.PI) this.brush.rotate(this.datas[i]/this.total*2*Math.PI) this.brush.lineTo(this.size/2,0) } this.brush.stroke() this.brush.closePath() this.brush.beginPath() this.brush.arc(0,0,this.blank/2,0,2*Math.PI) this.brush.lineWidth*=2 this.brush.stroke() this.brush.clip() this.brush.clearRect(-this.canvas.width/2,-this.canvas.height/2,this.canvas.width,this.canvas.height) this.brush.closePath() this.brush.restore() } Pie.prototype.put=function(dom){ dom.appendChild(this.canvas) } piedom=document.getElementsByClassName("pie")[0] new Pie(piedom.dataset.datas.split(","),piedom.dataset.size,piedom.dataset.blank).put(piedom) </script>