如何使用Chart.js API创建两个饼状图

How to create two pie charts using Chart.js API?

本文关键字:两个 Chart 何使用 js API 创建      更新时间:2023-09-26

这是我的HTML页面:

    <div>
        <canvas id="chart-area1" width="300" height="300"/>
    </div>
<script src="Chart.js"></script>
<script>
    var pieData1 = [
            {
                value: 300,
                color:"#F7464A",
                highlight: "#FF5A5E",
                label: "Red"
            },
            {
                value: 50,
                color: "#46BFBD",
                highlight: "#5AD3D1",
                label: "Green"
            },
            {
                value: 100,
                color: "#FDB45C",
                highlight: "#FFC870",
                label: "Yellow"
            },
            {
                value: 40,
                color: "#949FB1",
                highlight: "#A8B3C5",
                label: "Grey"
            },
            {
                value: 120,
                color: "#4D5360",
                highlight: "#616774",
                label: "Dark Grey"
            }
        ];
        window.onload = function(){
            var ctx1 = document.getElementById("chart-area1").getContext("2d");
            var myPie1 = new Chart(ctx1).Pie(pieData1);
        };

</script>
<div>
        <canvas id="chart-area2" width="300" height="300"/>
    </div>
<script src="Chart1.js"></script>
<script>
    var pieData2 = [
            {
                value: 300,
                color:"#F7464A",
                highlight: "#FF5A5E",
                label: "Red"
            },
            {
                value: 50,
                color: "#46BFBD",
                highlight: "#5AD3D1",
                label: "Green"
            },
            {
                value: 100,
                color: "#FDB45C",
                highlight: "#FFC870",
                label: "Yellow"
            },
            {
                value: 40,
                color: "#949FB1",
                highlight: "#A8B3C5",
                label: "Grey"
            },
            {
                value: 120,
                color: "#4D5360",
                highlight: "#616774",
                label: "Dark Grey"
            }
        ];
        window.onload = function(){
            var ctx2 = document.getElementById("chart-area2").getContext("2d");
            var myPie2 = new Chart(ctx2).Pie(pieData2);
        };

</script>

'Chart.js'和'Chart1.js'包含相同内容。我只使用过一次Chart.js,但它不起作用。所以我试了两个。

上面的HTML页面只显示一个饼状图。另一个饼状图不显示,但占据页面空间。

应该做什么更改才能显示两个饼状图?

您将window.onload设置为一个值两次,导致它被最新的值覆盖:

window.onload = function(){
    var ctx1 = document.getElementById("chart-area1").getContext("2d");
    var myPie1 = new Chart(ctx1).Pie(pieData1);
};
// ...
window.onload = function(){
    var ctx2 = document.getElementById("chart-area2").getContext("2d");
    var myPie2 = new Chart(ctx2).Pie(pieData2);
};

为什么不把这两个功能结合起来呢?

:

var func1 = function() { /* set up chart 1 */ },
    func2 = function() { /* set up chart 2 */ };
window.onload = function() {
    func1();
    func2();
};

问题是您重新分配了窗口。Onload,它只加载第二个。试着这样做:

window.onload = function(){
        var ctx1 = document.getElementById("chart-area1").getContext("2d");
        var myPie1 = new Chart(ctx1).Pie(pieData1);
        var ctx2 = document.getElementById("chart-area2").getContext("2d");
        var myPie2 = new Chart(ctx2).Pie(pieData2);
};
Here is the code for the pichat which worked for me. 
<link href="../JSfiles/Style.css" rel="stylesheet" />
    <script src="../ChartsJs/Chart.js"></script>
    <script src="../ChartsJs/Chart.min.js"></script>
    <script src="../ChartsJs/jquery-1.7.1.min.js"></script>
     <script src="http://www.chartjs.org/assets/Chart.min.js"></script>
     <script type="text/javascript">
             $(document).ready(function () {
             debugger;
             $.ajax({
                 type: 'POST',
                 dataType: 'json',
                 contentType: 'application/json',
                 url: 'PubPerformancePichat.aspx/GetDataonload',
                 data: {},
                 success: function (response) {
                     drawchart(response.d); // calling method
                 },
                 error: function () {
                     //alert("Error:Something went wrong.Contact the Adminstrator");
                     //alert(response);
                 }
             })
         });
         function drawchart(dataValues) {
             var arr = [];
             var arrcolor = '#231F20, #FFC200, #F44937, #16F27E, #FC9775, #5A69A6';
             var acolor = arrcolor.split(',');
             for (var i = 0; i < dataValues.length; i++) {
                 var obj = {};
                 obj.color = acolor[i];
                 obj.value = dataValues[i].Accountvalues;
                 obj.label = dataValues[i].Accounts;
                 arr.push(obj);
             }
             // Instantiate and draw our chart, passing in some options
             var ctx = $("#myChart").get(0).getContext("2d");
             var myPieChart = new Chart(ctx).Pie(arr);
         }
    </script>
---here is the CS File
        [WebMethod(EnableSession = true)]
        public static List<Chatdata> GetDataonload()
        {
            List<Chatdata> dataList = new List<Chatdata>();
            using (SqlConnection con = new SqlConnection("Data Source=203.115.195.52;Initial Catalog=mcom_ad_engine;Persist Security Info=True;User ID=appl;Password=mcom007;"))
            {
                string publisherid = "2000105";
                if (!string.IsNullOrEmpty(publisherid))
                {
                    //string StartDate = DateTime.Now.AddDays(-180).ToString("yyyy-MM-dd");
                    string StartDate = DateTime.Now.AddDays(-60).ToString("yyyy-MM-dd");
                    string EndDate = DateTime.Now.ToString("yyyy-MM-dd");
                    SqlCommand cmd = new SqlCommand("Sp_publisher_Totalunpaied_pichart", con);
                    cmd.CommandTimeout = 50;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@publisherid", publisherid);
                    cmd.Parameters.AddWithValue("@istartdate", StartDate);
                    cmd.Parameters.AddWithValue("@ienddate", EndDate);
                    con.Open();
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    da.SelectCommand = cmd;
                    DataTable dt = new DataTable();
                    da.Fill(dt);
                    con.Close();
                    foreach (DataRow dtrow in dt.Rows)
                    {
                        if (dtrow[0].ToString() != "Total Earned")
                        {
                            Chatdata details = new Chatdata();
                            details.Accounts = dtrow[0].ToString();
                            // details.spent = Convert.ToInt64(dtrow[2].ToString());
                            if (dtrow[1].ToString().StartsWith("-"))
                            {
                                string bal = dtrow[1].ToString();
                                bal = bal.Substring(1, bal.Length - 1);
                                details.Accountvalues = Convert.ToInt64(bal);
                            }
                            else
                            {
                                details.Accountvalues = Convert.ToInt64(dtrow[1].ToString());
                            }
                            dataList.Add(details);
                        }
                    }
                }
                else
                {
                    //navigate to Login Page
                }
                return dataList;
            }
        }