亲宝软件园·资讯

展开

canvas饼状图 javascript使用canvas实现饼状图效果

HaiRong_21 人气:0
想了解javascript使用canvas实现饼状图效果的相关内容吗,HaiRong_21在本文为您仔细讲解canvas饼状图的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:js,canvas,饼状图,下面大家一起来学习吧。

使用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>

加载全部内容

相关教程
猜你喜欢
用户评论