最近預計會有一些製作網頁的需求, 學著用 bootstrap5 與 chart.js, 碰到一些問題, 上網搜尋解答, 解決後做個紀錄
- Html head 加入 cdn:
<head> .. . <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/ 5.15.3/js/all.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js /bootstrap.bundle.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/chart.js@3.5.1/dist/ chart.js"></script> . . . </head> |
- 避免微軟EDGE 瀏覽器不相容 (IE11好像沒救了,只支援部分 HTML5)的CSS:
<style> canvas { -moz-user-select: none; -webkit-user-select: none; -ms-user-select: none; } </style> |
Plot_chart(): 在指定ctx 位置繪圖:
'use strict'; function plot_chart(ctx, chart_data, chart_labels) { var config = { type: "bar", data: { labels: chart_labels, datasets: [ { label: "Day", backgroundColor: "rgba(2,117,216,1)", borderColor: "rgba(2,117,216,1)", data: chart_data, }, ], }, options: { //responsive: true, plugins: { legend: { display: false, }, tooltip: { callbacks: { label: function(context) { var label = ''; if (context.parsed.y !== null) { label = context.parsed.y.toFixed(3); } return label; } } } }, }, }; var myChart = new Chart(ctx, config); return myChart; } |
- 繪圖函數plot_chart(),要注意,chart v3每次繪圖前須將原 chart 做 destroy,否則會報錯:
var chart1; //global in windws // plot_chart1(): find Chart1 and plot function plot_chart1() { const url = "api/get_chart1.php"; var ctx = document.getElementById("Chart1"); if (window.chart1 instanceof Chart) { //console.debug("destory chart1"); window.chart1.destroy(); } fetch(url) .then((resp) => resp.json()) .then(function (data) { var chart_data = data.data; var chart_labels = data.labels; //console.debug(chart_data); //console.debug(chart_labels); chart1 = plot_chart(ctx, chart_data, chart_labels); }); setTimeout(plot_chart1, 60000); } // plot the chart //setTimeout(plot_chart1, 1000); //alternative animation method plot_chart1(); |
- Html body 嵌入 js script:
<body> . . . <script type="text/javascript" src="js/get_sample.js"></script> <script type="text/javascript" src="js/plot_chart.js"></script> <script type="text/javascript" src="js/plot_chart1.js"></script> <script type="text/javascript" src="js/plot_chart2.js"></script> . . . </body> |
沒有留言:
張貼留言