Canvas使用chart.js

时间:2015-10-30 07:39:32

标签: javascript html canvas

enter image description here

如上图所示,canvas切断了饼图的边缘。我正在尝试调整画布的宽度和高度。当宽度较高时,将剪切底部,当高度较高时将剪切。

这是我在php for canvas中的代码:

            printf('<table>');
            echo '<tr><td style="text-align: right;"><canvas id="pie-canvas-'
                 . $canvasId
                 . '" width=256 height=256 style="width=300px;height=300px"></canvas></td><td style="text-align: left;width:360px;" id="legend" class="chart-legend"></td></tr>';

            echo '<script type="text/javascript">drawPie('
                . $canvasId
                . ', '
                . $data
                .', '
                . $legend
                . ');</script>';

使用Javascript:

    printf( '<script type="text/javascript" src="django/static/js/Chart.min.js"></script>' );
    printf( '<script type="text/javascript" src="extlib/jquery-min.js"></script>' );
    printf( '<script type="text/javascript">' );
    ?>
    function drawPie( canvasId, data, legend )
    {
        var canvas = document.getElementById("pie-canvas-" + canvasId);
        var ctx = canvas.getContext("2d");
        var midX = canvas.width/2;
        var midY = canvas.height/2;
        var piedata = [];

        $.each(data,function(i,val){
            piedata.push({value:val.count,color:val.color,label:val.status});
        });

        var myPieChart = new Chart(ctx).Pie(piedata, {
            showTooltips: false,
            onAnimationProgress: drawSegmentValues
        });

        var radius = myPieChart.outerRadius;

        function drawSegmentValues()
        {
            var length = myPieChart.segments.length;
            var totalValue = 0;
            for (var i=0; i< length; i++)
            {
                totalValue +=myPieChart.segments[i].value;
            }
            for(var i=0; i< length; i++)
            {
                ctx.fillStyle="black";
                var textSize = canvas.width/15;
                ctx.font= textSize+"px Verdana";

                // Get needed variables
                var value = Math.round(((myPieChart.segments[i].value)/totalValue)*100);
                var startAngle = myPieChart.segments[i].startAngle;
                var endAngle = myPieChart.segments[i].endAngle;
                var middleAngle = startAngle + ((endAngle - startAngle)/2);

                // Compute text location
                var posX = (radius/1.5) * Math.cos(middleAngle) + midX;
                var posY = (radius/1.5) * Math.sin(middleAngle) + midY;

                // Text offside by middle
                var w_offset = ctx.measureText(value).width/2;
                var h_offset = textSize/4;

                ctx.fillText(value+"%", posX - w_offset, posY + h_offset);
            }
        }

        if(legend)document.getElementById("legend").innerHTML = myPieChart.generateLegend();
    }
    <?php
    printf('</script>');

你能告诉我如何解决这个并得到完美的图表吗?

0 个答案:

没有答案