Chart.js 是一套開放原始碼的「圖表」繪製函式庫,和其他第三方的圖表工具相比,Chart.js 的特色如下:
- 支援 HTML 5、響應式網頁 (RWD, Responsive Web Design)
- 可免費使用,且可作為商業用途
- 開放原始碼 (GitHub)
- 可用 JavaScript 操作及開發
- 可與 JSON 格式整合,因此能與 ASP.NET MVC、ASP.NET WebAPI、AJAX 技術作整合,便於資料傳遞
圖 1 本文範例的執行畫面 (.html、.cshtml)
-------------------------------------------------
本文的 ASP.NET MVC 範例下載:
https://files.cnblogs.com/files/WizardWu/190101.zip
---------------------------------------------------
Chart.js 官方網站:
https://www.chartjs.org/
Chart.js 使用方式:
Visual Studio 中的引用方式,用 NuGet 安裝 Chart.js,並在頁面中引用 Chart.min.js。
----------------------------------------------------------------------------------------------------------------------------------------
以下的範例 1,以單純的 .html 來測試 Chart.js (不使用 .NET / C#)。資料來源,是寫死在頁面裡的 JavaScript。
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8" /> 5 <title></title> 6 <!--<link href="../Content/bootstrap.min.css" rel="stylesheet" />--> 7 <script src="../Scripts/Chart.min.js"></script> 8 </head> 9 <body> 10 <canvas id="myChart"></canvas> 11 12 <script> 13 var ctx = document.getElementById("myChart"); 14 var chart = new Chart(ctx, { 15 type: "line", 16 data: { 17 labels: ['1月', '2月', '3月', '4月', '5月', '6月'], 18 datasets: [{ 19 label: "台北", 20 fill: false, 21 backgroundColor: 'rgba(255,165,0,0.3)', 22 borderColor: 'rgb(255,135,20)', 23 pointStyle: "circle", 24 pointBackgroundColor: 'rgb(0,222,0)', 25 pointRadius: 5, 26 pointHoverRadius: 10, 27 data: [13.1, 10.2, 13.5, 20.9, 25.2, 27.1, 31.8] 28 }, { 29 label: "高雄", 30 fill: false, 31 backgroundColor: 'rgba(0,255,255,0.3)', 32 borderColor: 'rgb(0,225,255)', 33 pointStyle: "triangle", 34 pointBackgroundColor: 'blue', 35 pointRadius: 5, 36 pointHoverRadius: 10, 37 data: [29.1, 28.3, 22.6, 25.4, 27.5, 23.4] 38 39 }, { 40 label: "越南", 41 fill: false, 42 backgroundColor: 'rgba(153,50,204,0.3)', 43 borderColor: 'rgb(123,55,190)', 44 pointStyle: "rect", 45 pointBackgroundColor: 'rgb(220,20,60)', 46 pointRadius: 5, 47 pointHoverRadius: 10, 48 data: [16.6, 17.3, 19.2, 23.8, 12.0, 17.6] 49 50 }] 51 }, 52 options: { 53 responsive: true, 54 title: { 55 display: true, 56 fontSize: 26, 57 text: '2019 年各分公司 1 - 6 月份營業額' 58 }, 59 tooltips: { 60 mode: 'point', 61 intersect: true, 62 }, 63 hover: { 64 mode: 'nearest', 65 intersect: true 66 }, 67 scales: { 68 xAxes: [{ 69 display: true, 70 scaleLabel: { 71 display: true, 72 labelString: '月份', 73 fontSize: 15 74 }, 75 ticks: { 76 fontSize: 15 77 } 78 }], 79 yAxes: [{ 80 display: true, 81 scaleLabel: { 82 display: true, 83 labelString: '百萬(美元)', 84 fontSize: 15 85 }, 86 ticks: { 87 fontSize: 15 88 } 89 }] 90 }, 91 animation: { 92 duration: 2000 93 } 94 } 95 }); 96 </script> 97 </body> 98 </html>