SVG画饼状图

by Mike Lin

HTML

<body>

</body>

JavaScript

var data = {
        size: 230,
        sectors: [
            {
                percentage: 0.43,
                label: 'Thing 1'
            },
            {
                percentage: 0.22,
                label: "Thing Two"
            },
            {
                percentage: 0.18,
                label: "Another Thing"
            },
            {
                percentage: 0.17,
                label: "Pineapple"
            }
        ]
    }

    function calculateSectors( data ) {
        var sectors = [];
        var colors = [
            "#61C0BF", "#DA507A", "#BB3D49", "#DB4547"
        ];

        var l = data.size / 2
        var a = 0 // Angle
        var aRad = 0 // Angle in Rad
        var z = 0 // Size z
        var x = 0 // Side x
        var y = 0 // Side y
        var X = 0 // SVG X coordinate
        var Y = 0 // SVG Y coordinate
        var R = 0 // Rotation


        data.sectors.map( function(item, key ) {
            a = 360 * item.percentage;
            aCalc = ( a > 180 ) ? 360 - a : a;
            aRad = aCalc * Math.PI / 180;
            z = Math.sqrt( 2*l*l - ( 2*l*l*Math.cos(aRad) ) );
            if( aCalc <= 90 ) {
                x = l*Math.sin(aRad);
            }
            else {
                x = l*Math.sin((180 - aCalc) * Math.PI/180 );
            }
            
            y = Math.sqrt( z*z - x*x );
            Y = y;

            if( a <= 180 ) {
                X = l + x;
                arcSweep = 0;
            }
            else {
                X = l - x;
                arcSweep = 1;
            }
            let t, tx, ty;
            // 计算文本框的位置
            if (a < 180) {
            	t = l * Math.cos(aRad/2)
              tx = t * Math.sin(aRad/2) + l
              ty = l - t*Math.sin(aRad/2)
            }

            sectors.push({
                percentage: item.percentage,
                label: item.label,
                color: colors[key],
                arcSweep: arcSweep,
               ...