canvas 饼图切线

微信图片_20240418160317.png
<!DOCTYPE html>
<html>
<head>
  <title> Pie Charts</title>
</head>

<body>
  <canvas id="pieChartCanvas" width="400" height="400"></canvas>

  <script>
    var canvas = document.getElementById("pieChartCanvas");
    var ctx = canvas.getContext("2d");
    const circlePoints = []
    function drawLine(ctx, pointStart, pointEnd) {
      ctx.beginPath();
      ctx.moveTo(pointStart.x, pointStart.y);
      ctx.lineTo(pointEnd.x, pointEnd.y);
      ctx.stroke();
    }
    var data1 = [
      { label: "Slice 1", value: 20, color: "#FF5733" },
      { label: "Slice 2", value: 80, color: "#FFC300" }
    ];

    var data2 = [
      { label: "Slice 1", value: 10, color: "#36A2EB" },
      { label: "Slice 2", value: 90, color: "#8E44AD" }
    ];

    function drawPieChart(data, centerX, centerY, radius, rotation) {
      var total = data.reduce((sum, slice) => sum + slice.value, 0);
      var minSlice = data.reduce(function (prev, current) {
        return (prev.value < current.value) ? prev : current;
      });
      var minSliceAngle = (minSlice.value / 100) * Math.PI * 2;

      var startAngle = rotation - minSliceAngle / 2;

      for (var i = 0; i < data.length; i++) {
        var sliceAngle = (data[i].value / total) * 2 * Math.PI;

        // Calculate intersection point with the circle at the segment boundary
        var angle = startAngle + sliceAngle;
        var x = centerX + radius * Math.cos(angle);
        var y = centerY + radius * Math.sin(angle);
        circlePoints.push({ x: x, y: y })
        // Draw the slice
        ctx.beginPath();
        ctx.moveTo(centerX, centerY);
        ctx.arc(centerX, centerY, radius, startAngle, startAngle + sliceAngle);
        ctx.closePath();
        ctx.fillStyle = data[i].color;
        ctx.fill();

        // Draw a point at the segment boundary
        ctx.beginPath();
        ctx.arc(x, y, 5, 0, 2 * Math.PI);
        ctx.fillStyle = "#000";
        ctx.fill();

        // Update the starting angle for the next slice
        startAngle += sliceAngle;
      }
    }

    // Draw the two pie charts
    // drawPieChart(data1, canvas.width / 4, canvas.height / 2, 100, -Math.PI / 4);
    // drawPieChart(data2, canvas.width * 3 / 4, canvas.height / 2, 100, -Math.PI / 4 - Math.PI / 2);
    drawPieChart(data1, canvas.width / 4, canvas.height / 2, 50, 0);
    drawPieChart(data2, canvas.width * 3 / 4, canvas.height / 2, 50, 0);
    //

    drawLine(ctx, circlePoints[0], circlePoints[2],)
    drawLine(ctx, circlePoints[1], circlePoints[3],)
  </script>
</body>

</html>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容