欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

javascript使用canvas实现饼状图效果

程序员文章站 2022-06-22 11:34:47
使用canvas写一个饼状图,供大家参考,具体内容如下代码:

使用canvas写一个饼状图,供大家参考,具体内容如下

javascript使用canvas实现饼状图效果

代码:

<!doctype html>
<html lang="en">

<head>
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>document</title>
</head>

<body>
 <canvas id='canvas' width='800' height='400' style="border: 1px solid red;"></canvas>

 <script>
  let data = [
   { title: "服饰1", money: 400 },
   { title: "服饰2", money: 300 },
   { title: "服饰3", money: 400 },
   { title: "服饰4", money: 200 },
   { title: "服饰5", money: 500 },
   { title: "服饰6", money: 180 },
   { title: "服饰7", money: 500 }]

  /** @type {htmlcanvaselement} */
  let canvas = document.queryselector("#canvas");
  let ctx = canvas.getcontext("2d");
  let r = 100;

  let money = function (obj, sum) {
   for (let i = 0; i < obj.length; i++) {
    sum += data[i].money
    
   }
   return sum;
  }
  let totalmoney = money(data, 0);

  let nowsum = 0;
  let start = 0;
  let end = 0;
  let r = 100;
  let i=0;
  data.foreach(function (item) {
   ctx.beginpath()
   nowsum += item.money;
   end = (nowsum / totalmoney) 
   ctx.moveto(150, 150);
   ctx.arc(150, 150, r, start*math.pi*2, end*math.pi*2)
   start = end;
   //产生随机颜色
   ctx.fillstyle = '#' + math.floor(math.random() * 0xffffff).tostring(16);
   ctx.rect(350,5+(35*i),30,30);
   ctx.font="14px 黑体"
   ctx.filltext(item.title,400,25+(35*i))
   ctx.strokestyle = "gray"
   ctx.fill();
   ctx.stroke();
   i++;
  })
 </script>
</body>

</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。