text-to-chart.js 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401
  1. console.log('text-to-chart');
  2. var accessToken = localStorage.getItem("access_token");
  3. console.log(accessToken);
  4. if (accessToken === null) {
  5. alert('請先登入')
  6. window.location.href = "./login.html";
  7. }
  8. var usernameEmail = localStorage.getItem("username");
  9. var unit_table_value
  10. // let username = usernameEmail.split('@')[0];
  11. Chart.register(ChartDataLabels);
  12. var userNameSpan = document.getElementById("userName");
  13. var lineYfontSize = document.getElementById("lineYfontSize");
  14. userNameSpan.textContent = usernameEmail;
  15. var inputField = document.getElementById("keyword_data");
  16. var inputField_compare = document.getElementById("keyword_data_compare");
  17. var sendButton = document.getElementById("send_data");
  18. var canvasPng = document.getElementById("textToChart");
  19. var img_box = document.getElementById("img_box");
  20. var sidebar = document.getElementById('style_setting');
  21. var input_text_value;
  22. var chartType = 'line';
  23. var unit = '';
  24. var myChart = null;
  25. var chartColor = '#912B2B';
  26. var chartColorBar = '#'
  27. var displayXaxes = true;
  28. var ctx;
  29. var chartlabels;
  30. var chartdata;
  31. var XfontSizeValue = 18;
  32. var YfontSizeValue = 18;
  33. var TitlefontSizeValue = 32;
  34. var chart_bgimg_url = "url(./img/bg06.webp)";
  35. var vocab = [];
  36. var chartDiv = document.getElementById('chartdiv');
  37. $('#chartdiv').hide();
  38. document.addEventListener('DOMContentLoaded', function () {
  39. axios.get("https://cmm.ai:8080/vocab")
  40. .then(response => {
  41. // apiHideLoading();
  42. console.log(response);
  43. vocab = response.data;
  44. })
  45. .catch(error => {
  46. console.error('發生錯誤:', error);
  47. });
  48. });
  49. inputField.addEventListener('click', function () {
  50. // 確保輸入框處於焦點狀態
  51. inputField.focus();
  52. // 在控制台中顯示焦點狀態
  53. console.log('Input field focused');
  54. });
  55. document.addEventListener('DOMContentLoaded', function () {
  56. // const input = document.getElementById('stockInput');
  57. const suggestions = document.getElementById('suggestions');
  58. inputField.addEventListener('input', function () {
  59. const query = this.value.trim();
  60. suggestions.innerHTML = ''; // 清空之前的建議
  61. console.log('query', query);
  62. if (query) {
  63. // const filteredVocab = vocab.filter(item => item.toLowerCase().includes(query));
  64. const queryTerms = query.split(/\s+/); // 分割輸入的內容
  65. const lastQueryTerm = queryTerms[queryTerms.length - 1];
  66. const filteredVocab = vocab.filter(item => {
  67. // 對每個分割後的單詞進行匹配,只要其中有一個匹配成功就返回 true
  68. return item.toLowerCase().includes(lastQueryTerm.toLowerCase());
  69. });
  70. if (filteredVocab.length > 0) {
  71. suggestions.style.border = '1px solid #ccc';
  72. suggestions.style.display = 'block'; // 顯示建議容器
  73. } else {
  74. suggestions.style.border = 'none';
  75. suggestions.style.display = 'none'; // 隱藏建議容器
  76. }
  77. console.log(queryTerms[queryTerms.length - 1])
  78. filteredVocab.forEach(item => {
  79. const div = document.createElement('div');
  80. div.classList.add('autocomplete-suggestion');
  81. div.textContent = item;
  82. // div.addEventListener('click', function () {
  83. // inputField.value = item;
  84. // suggestions.innerHTML = ''; // 清空建議
  85. // suggestions.style.border = 'none';
  86. // suggestions.style.display = 'none'; // 隱藏建議容器
  87. // });
  88. console.log('queryTerms', queryTerms);
  89. // console.log('filteredVocab', filteredVocab);
  90. div.addEventListener('click', function () {
  91. queryTerms.forEach((term, index) => {
  92. const regex = new RegExp(term, 'gi');
  93. const match = regex.exec(inputField.value);
  94. // console.log(queryTerms[queryTerms.length - 1]);
  95. // console.log(filteredVocab, queryTerms[queryTerms.length - 1])
  96. if (index === queryTerms.length - 1) {
  97. if (match) {
  98. var start = match.index;
  99. var end = start + match[0].length;
  100. console.log(start, end)
  101. const textBefore = inputField.value.substring(0, start);
  102. const textAfter = inputField.value.substring(end, inputField.value.length);
  103. console.log('start', start, 'end', end, 'textBefore', textBefore, 'textAfter', textAfter);
  104. // 捕獲被選中的部分並替換它
  105. const selectedText = inputField.value.substring(start, end);
  106. console.log('selectedText', selectedText);
  107. const newText = textBefore + item + textAfter.replace(selectedText, '');
  108. console.log('newText', newText);
  109. inputField.value = newText;
  110. // inputField.value = textBefore + item.replace(selectedText, '') + textAfter;
  111. suggestions.innerHTML = ''; // 清空建議
  112. suggestions.style.border = 'none';
  113. }
  114. }
  115. });
  116. // const start = inputField.selectionStart;
  117. // const end = inputField.selectionEnd;
  118. });
  119. suggestions.appendChild(div);
  120. });
  121. } else {
  122. suggestions.style.border = 'none';
  123. suggestions.style.display = 'none'; // 隱藏建議容器
  124. }
  125. });
  126. });
  127. document.addEventListener('DOMContentLoaded', function () {
  128. // const input = document.getElementById('stockInput');
  129. const suggestions_compare = document.getElementById('suggestions_compare');
  130. inputField_compare.addEventListener('input', function () {
  131. const query = this.value.trim();
  132. suggestions_compare.innerHTML = ''; // 清空之前的建議
  133. console.log('query', query);
  134. if (query) {
  135. // const filteredVocab = vocab.filter(item => item.toLowerCase().includes(query));
  136. const queryTerms = query.split(/\s+/); // 分割輸入的內容
  137. const lastQueryTerm = queryTerms[queryTerms.length - 1];
  138. const filteredVocab = vocab.filter(item => {
  139. // 對每個分割後的單詞進行匹配,只要其中有一個匹配成功就返回 true
  140. return item.toLowerCase().includes(lastQueryTerm.toLowerCase());
  141. });
  142. if (filteredVocab.length > 0) {
  143. suggestions_compare.style.border = '1px solid #ccc';
  144. suggestions_compare.style.display = 'block'; // 顯示建議容器
  145. } else {
  146. suggestions_compare.style.border = 'none';
  147. suggestions_compare.style.display = 'none'; // 隱藏建議容器
  148. }
  149. console.log(queryTerms[queryTerms.length - 1])
  150. filteredVocab.forEach(item => {
  151. const div = document.createElement('div');
  152. div.classList.add('autocomplete-suggestion');
  153. div.textContent = item;
  154. // div.addEventListener('click', function () {
  155. // inputField.value = item;
  156. // suggestions.innerHTML = ''; // 清空建議
  157. // suggestions.style.border = 'none';
  158. // suggestions.style.display = 'none'; // 隱藏建議容器
  159. // });
  160. console.log('queryTerms', queryTerms);
  161. // console.log('filteredVocab', filteredVocab);
  162. div.addEventListener('click', function () {
  163. queryTerms.forEach((term, index) => {
  164. const regex = new RegExp(term, 'gi');
  165. const match = regex.exec(inputField_compare.value);
  166. // console.log(queryTerms[queryTerms.length - 1]);
  167. // console.log(filteredVocab, queryTerms[queryTerms.length - 1])
  168. if (index === queryTerms.length - 1) {
  169. if (match) {
  170. var start = match.index;
  171. var end = start + match[0].length;
  172. console.log(start, end)
  173. const textBefore = inputField_compare.value.substring(0, start);
  174. const textAfter = inputField_compare.value.substring(end, inputField_compare.value.length);
  175. console.log('start', start, 'end', end, 'textBefore', textBefore, 'textAfter', textAfter);
  176. // 捕獲被選中的部分並替換它
  177. const selectedText = inputField_compare.value.substring(start, end);
  178. console.log('selectedText', selectedText);
  179. const newText = textBefore + item + textAfter.replace(selectedText, '');
  180. console.log('newText', newText);
  181. inputField_compare.value = newText;
  182. // inputField.value = textBefore + item.replace(selectedText, '') + textAfter;
  183. suggestions_compare.innerHTML = ''; // 清空建議
  184. suggestions_compare.style.border = 'none';
  185. }
  186. }
  187. });
  188. // const start = inputField.selectionStart;
  189. // const end = inputField.selectionEnd;
  190. });
  191. suggestions_compare.appendChild(div);
  192. });
  193. } else {
  194. suggestions_compare.style.border = 'none';
  195. suggestions_compare.style.display = 'none'; // 隱藏建議容器
  196. }
  197. });
  198. });
  199. // 監聽輸入框的鍵盤事件
  200. // document.getElementById("keyword_data").addEventListener("keyup", function (event) {
  201. // // 判斷是否按下 Enter 鍵 (key code: 13)
  202. // if (event.keyCode === 13) {
  203. // // 觸發送出按鈕的點擊事件
  204. // document.getElementById("send_data").click();
  205. // }
  206. // });
  207. // 定義按鈕點擊事件處理函數
  208. function sendButtonClickHandler() {
  209. console.log(inputField.value);
  210. var input_text_value = inputField.value;
  211. $('#chartdiv').hide();
  212. sidebar.classList.remove('show');
  213. sidebar.classList.add('hidden');
  214. // 在這裡添加你希望在按下按鈕時執行的其他代碼
  215. get_data(input_text_value);
  216. }
  217. sendButton.addEventListener("click", sendButtonClickHandler);
  218. // sendButton.addEventListener("click", function () {
  219. // console.log(inputField.value);
  220. // input_text_value = inputField.value;
  221. // // if (myChart) {
  222. // // console.log('已存在')
  223. // // data = [];
  224. // // labels = [];
  225. // // myChart.removePlugin(Chart.pluginService.getPlugin('afterDraw'));
  226. // // myChart.destroy();
  227. // // }
  228. // get_data(input_text_value);
  229. // });
  230. var lastKeyPressTime = 0;
  231. var enterCount = 0;
  232. var ENTER_THRESHOLD = 500; // 設定連續按下 Enter 的時間閾值(毫秒)
  233. inputField.addEventListener("keyup", function (event) {
  234. // 判斷是否按下 Enter 鍵 (key code: 13)
  235. if (event.key === "Enter") {
  236. var currentTime = new Date().getTime();
  237. // 計算與上一次按鍵按下時間的差值
  238. var timeDiff = currentTime - lastKeyPressTime;
  239. lastKeyPressTime = currentTime;
  240. // 如果兩次 Enter 鍵按下的時間差小於閾值,則增加計數器
  241. if (timeDiff <= ENTER_THRESHOLD) {
  242. enterCount++;
  243. // 如果計數器為2,則觸發 API 請求並重置計數器
  244. if (enterCount === 2) {
  245. sendButtonClickHandler();
  246. enterCount = 0;
  247. }
  248. } else {
  249. // 如果時間差大於閾值,則重置計數器
  250. enterCount = 0;
  251. }
  252. } else {
  253. // 如果按下的不是 Enter 鍵,則重置計數器
  254. enterCount = 0;
  255. }
  256. });
  257. function number_format(number, decimals, dec_point, thousands_sep) {
  258. // * example: number_format(1234.56, 2, ',', ' ');
  259. // * return: '1 234,56'
  260. number = (number + '').replace(',', '').replace(' ', '');
  261. var n = !isFinite(+number) ? 0 : +number,
  262. prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
  263. sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
  264. dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
  265. s = '',
  266. toFixedFix = function (n, prec) {
  267. var k = Math.pow(10, prec);
  268. return '' + Math.round(n * k) / k;
  269. };
  270. // Fix for IE parseFloat(0.55).toFixed(0) = 0;
  271. s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
  272. if (s[0].length > 3) {
  273. s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
  274. }
  275. if ((s[1] || '').length < prec) {
  276. s[1] = s[1] || '';
  277. s[1] += new Array(prec - s[1].length + 1).join('0');
  278. }
  279. return s.join(dec);
  280. }
  281. var labels = [];
  282. var data = [];
  283. function apiLoading() {
  284. document.getElementById('chartDataLoading').style.display = 'block';
  285. }
  286. function apiHideLoading() {
  287. document.getElementById('chartDataLoading').style.display = 'none';
  288. }
  289. const DISPLAY = true;
  290. const BORDER = true;
  291. const CHART_AREA = true;
  292. const TICKS = true;
  293. var labels = [];
  294. var data = [];
  295. var dataArray;
  296. function generateChart(dataArray) {
  297. if (dataArray.length > 10) {
  298. lineYfontSize.style.display = 'none'
  299. } else {
  300. lineYfontSize.style.display = 'block'
  301. }
  302. // 创建一个空数组来存储 labels 和 data
  303. console.log(dataArray)
  304. // 遍历数据数组
  305. for (var i = 0; i < dataArray.length; i++) {
  306. var item = dataArray[i];
  307. // 遍历当前项的属性
  308. for (var key in item) {
  309. // 如果属性名不在 labels 数组中,并且属性值不是对象,则将属性名添加到 labels 数组中
  310. if (typeof item[key] === 'string') {
  311. labels.push(item[key]);
  312. }
  313. // 如果属性值是数值类型,则将其添加到 data 数组中
  314. if (typeof item[key] === 'number') {
  315. data.push(item[key]);
  316. }
  317. }
  318. }
  319. console.log(data);
  320. if (myChart) {
  321. console.log('已存在')
  322. myChart.destroy();
  323. }
  324. if (chartType === "doughnut") {
  325. // createChartDoughnut(chartType, data, labels);
  326. // createChartDoughnut2(data, labels)
  327. } else {
  328. createChart(chartType, data, labels);
  329. }
  330. // console.log(data);
  331. console.log(labels);
  332. }
  333. var amChartInstance;
  334. function extractAndGenerateChart(dataArray) {
  335. for (var i = 0; i < dataArray.length; i++) {
  336. var item = dataArray[i];
  337. // 遍历当前项的属性
  338. for (var key in item) {
  339. // 如果属性名不在 labels 数组中,并且属性值不是对象,则将属性名添加到 labels 数组中
  340. if (typeof item[key] === 'string') {
  341. labels.push(item[key]);
  342. }
  343. // 如果属性值是数值类型,则将其添加到 data 数组中
  344. if (typeof item[key] === 'number') {
  345. data.push(item[key]);
  346. }
  347. }
  348. }
  349. // console.log('key', key);
  350. generateBarChart(key, dataArray);
  351. }
  352. // 圓餅圖
  353. function generatePieChart(dataArray) {
  354. $('#chartdiv').show();
  355. bgImgelement.style.backgroundImage = chart_bgimg_url;
  356. // chartDiv.style.width = "100%"
  357. chartWhitelement.style.background = "rgba(255,255,255,0.5)"
  358. // Themes begin
  359. am4core.useTheme(am4themes_animated);
  360. // Themes end
  361. // Create chart instance
  362. var chart = am4core.create("chartdiv", am4charts.PieChart);
  363. chart.data = dataArray;
  364. chart.innerRadius = am4core.percent(50);
  365. // Add and configure Series
  366. var pieSeries = chart.series.push(new am4charts.PieSeries());
  367. pieSeries.dataFields.value = "y";
  368. pieSeries.dataFields.category = "x";
  369. pieSeries.slices.template.stroke = am4core.color("#fff");
  370. pieSeries.slices.template.strokeWidth = 2;
  371. pieSeries.slices.template.strokeOpacity = 1;
  372. // Configure labels
  373. pieSeries.labels.template.wrap = true;
  374. pieSeries.labels.template.maxWidth = 100;
  375. pieSeries.labels.template.truncate = false;
  376. pieSeries.labels.template.fontSize = 14;
  377. // Configure label text to wrap and show percentages
  378. pieSeries.labels.template.adapter.add("textOutput", function (text, target) {
  379. if (target.dataItem && target.dataItem.values.value.percent) {
  380. return "[font-size: 14px]" + target.dataItem.category + ": " + target.dataItem.values.value.percent.toFixed(1) + "%";
  381. }
  382. return text;
  383. });
  384. pieSeries.colors.list = [
  385. am4core.color('rgb(171, 51, 49)'),
  386. am4core.color('rgb(34, 83, 149)'),
  387. am4core.color('rgb(79, 148, 65)'),
  388. am4core.color('rgb(217, 195, 105)'),
  389. am4core.color('rgb(142, 124, 180)'),
  390. am4core.color('rgb(211, 183, 144)'),
  391. am4core.color('rgb(83, 84, 84)'),
  392. am4core.color('rgb(229, 147, 152)')
  393. ];
  394. // Ensure labels have background
  395. // pieSeries.labels.template.background.fillOpacity = 1;
  396. console.log(pieSeries.labels.template)
  397. // Set label background color to match corresponding slice color
  398. pieSeries.labels.template.adapter.add("background.fill", function (fill, target) {
  399. return target.dataItem.slice.fill;
  400. });
  401. // This creates initial animation
  402. pieSeries.hiddenState.properties.opacity = 1;
  403. pieSeries.hiddenState.properties.endAngle = -90;
  404. pieSeries.hiddenState.properties.startAngle = -90;
  405. // console.log('調位置')
  406. downloadButton.style.display = "inline-block";
  407. }
  408. // var colorEven='#288D97';
  409. // var colorOdd='#427D7E'
  410. function adjustColorBrightness(color, amount) {
  411. let usePound = false;
  412. if (color[0] == "#") {
  413. color = color.slice(1);
  414. usePound = true;
  415. }
  416. let num = parseInt(color, 16);
  417. let r = (num >> 16) + amount;
  418. let g = ((num >> 8) & 0x00FF) + amount;
  419. let b = (num & 0x0000FF) + amount;
  420. if (r > 255) r = 255;
  421. else if (r < 0) r = 0;
  422. if (g > 255) g = 255;
  423. else if (g < 0) g = 0;
  424. if (b > 255) b = 255;
  425. else if (b < 0) b = 0;
  426. return (usePound ? "#" : "") + (r << 16 | g << 8 | b).toString(16).padStart(6, '0');
  427. }
  428. // 柱狀圖
  429. function generateBarChart(key, dataArray) {
  430. $('#chartdiv').show();
  431. // var colorEven = document.getElementById('colorEven').value;
  432. // var colorOdd = document.getElementById('colorOdd').value;
  433. var baseColor = document.getElementById('borderColorInputBar').value;
  434. var categoryAxisFzValue = document.getElementById('XfontSizeBar').value;
  435. var valueAxisFzValue = document.getElementById('YfontSizeBar').value;
  436. var colorEven = am4core.color(baseColor);
  437. var colorOdd = adjustColorBrightness(baseColor, -20);
  438. chartDiv.style.fontFamily = "Arial, sans-serif";
  439. chartDiv.style.fontWeight = "900";
  440. bgImgelement.style.backgroundImage = chart_bgimg_url;
  441. chartWhitelement.style.background = "rgba(255,255,255,0.5)"
  442. console.log('labelDependent', labelDependent);
  443. // Themes begin
  444. am4core.useTheme(am4themes_animated);
  445. // Themes end
  446. // Create chart instance
  447. var chart = am4core.create("chartdiv", am4charts.XYChart3D);
  448. console.log('判斷資料', dataArray);
  449. chart.data = dataArray;
  450. chart.angle = 30; // 圖表角度
  451. chart.depth = 25; // 圖表深度
  452. let categoryAxis = chart.xAxes.push(new am4charts.CategoryAxis());
  453. categoryAxis.dataFields.category = "x";
  454. categoryAxis.renderer.labels.template.rotation = 0;
  455. categoryAxis.renderer.labels.template.hideOversized = false;
  456. categoryAxis.renderer.minGridDistance = 20; // 間距
  457. // categoryAxis.renderer.labels.template.horizontalCenter = "left";
  458. // categoryAxis.renderer.labels.template.verticalCenter = "middle";
  459. // categoryAxis.tooltip.label.rotation = 90;
  460. // categoryAxis.tooltip.label.horizontalCenter = "right";
  461. // categoryAxis.tooltip.label.verticalCenter = "middle";
  462. // label 換行
  463. let label = categoryAxis.renderer.labels.template;
  464. label.wrap = true;
  465. if (dataArray.length > 5) {
  466. console.log('資料長度5')
  467. label.maxWidth = 50;
  468. } else {
  469. label.maxWidth = 100;
  470. console.log('資料長度<5')
  471. }
  472. // x軸字體大小
  473. categoryAxis.renderer.labels.template.fontSize = categoryAxisFzValue;
  474. categoryAxis.renderer.cellEndLocation = 0.5; // 減少值可以增加間距
  475. let valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
  476. valueAxis.title.text = labelDependent; // Y軸
  477. valueAxis.title.fontWeight = "bold";
  478. // y軸字體大小
  479. valueAxis.renderer.labels.template.fontSize = valueAxisFzValue;
  480. // Create series
  481. var series = chart.series.push(new am4charts.ColumnSeries3D());
  482. series.dataFields.valueY = 'y';
  483. series.dataFields.categoryX = "x";
  484. series.name = "y";
  485. series.tooltipText = "{categoryX}: [bold]{valueY}[/]";
  486. series.columns.template.fillOpacity = .8;
  487. let columnTemplate = series.columns.template;
  488. columnTemplate.strokeWidth = 2;
  489. columnTemplate.strokeOpacity = 1;
  490. columnTemplate.stroke = am4core.color("#FFFFFF");
  491. // columnTemplate.adapter.add("fill", function (fill, target) {
  492. // return chart.colors.getIndex(target.dataItem.index);
  493. // })
  494. // 設置基數和偶數顏色
  495. columnTemplate.adapter.add("fill", function (fill, target) {
  496. return target.dataItem.index % 2 === 0 ? am4core.color(colorEven) : am4core.color(colorOdd);
  497. });
  498. columnTemplate.adapter.add("stroke", function (stroke, target) {
  499. return chart.colors.getIndex(target.dataItem.index);
  500. })
  501. // // 加上白色線條
  502. // series.columns.template.events.on("validated", function (event) {
  503. // let column = event.target;
  504. // let whiteLine = column.createChild(am4core.Line);
  505. // whiteLine.stroke = am4core.color("#ffffff");
  506. // whiteLine.strokeWidth = 1.3; // 線條寬度
  507. // whiteLine.strokeOpacity = 0.5;// 透明度
  508. // whiteLine.x1 = column.pixelWidth / 1;
  509. // whiteLine.y1 = 0;
  510. // whiteLine.x2 = column.pixelWidth / 1;
  511. // whiteLine.y2 = column.pixelHeight;
  512. // });
  513. chart.cursor = new am4charts.XYCursor();
  514. chart.cursor.lineX.strokeOpacity = 0;
  515. chart.cursor.lineY.strokeOpacity = 0;
  516. categoryAxis.renderer.grid.template.strokeOpacity = 0; // 隱藏 X 軸
  517. // valueAxis.renderer.grid.template.strokeOpacity = 0; // 隱藏 Y 軸
  518. // valueAxis.renderer.line.strokeOpacity = 0;
  519. // LineSeries 底部線條
  520. var lineSeries = chart.series.push(new am4charts.LineSeries());
  521. lineSeries.dataFields.valueY = "bottom";
  522. lineSeries.dataFields.categoryX = "0";
  523. lineSeries.stroke = am4core.color("#FFFFFF")
  524. lineSeries.strokeWidth = 2;
  525. lineSeries.strokeOpacity = 1
  526. var bottomData = [];
  527. for (var i = 0; i < dataArray.length; i++) {
  528. bottomData.push({ "x": dataArray[i].x, "bottom": 0 });
  529. }
  530. lineSeries.data = bottomData;
  531. downloadButton.style.display = "inline-block";
  532. // 底部線條
  533. // let rectElements = document.querySelectorAll("rect");
  534. // // let widthValue = 0;
  535. // let fifthRectElement = rectElements[3];
  536. // // fifthRectElement.style.position = "relative";
  537. // setTimeout(() => {
  538. // let width = fifthRectElement.getAttribute("width");
  539. // // widthValue = parseFloat(width);
  540. // console.log('rectElements', rectElements);
  541. // console.log('fifthRectElement', fifthRectElement);
  542. // console.log('width', width);
  543. // let line = document.createElement("div");
  544. // line.style.position = "absolute";
  545. // line.style.bottom = "162px";
  546. // line.style.right = "40px";
  547. // line.style.width = `${parseFloat(width)}px`;
  548. // line.style.height = "2px";
  549. // line.style.backgroundColor = "#000000";
  550. // document.getElementById("chartdiv").appendChild(line);
  551. // }, 10)
  552. // end am4core.ready()
  553. }
  554. var downloadButton = document.getElementById("downloadButton");
  555. // downloadButton.style.display = 'none';
  556. // 添加點擊事件監聽器
  557. downloadButton.addEventListener('click', function () {
  558. setTimeout(function () {
  559. html2canvas(document.getElementById('data_chart_box')).then(function (canvas) {
  560. // // 獲取圖片資料 URL
  561. // var imageData = canvasPng.toDataURL("image/png");
  562. // // 創建下載連結
  563. // var link = document.createElement('a');
  564. // link.download = 'chart.png'; // 下載的檔案名稱
  565. // link.href = imageData; // 圖片資料 URL
  566. // // 模擬點擊下載連結
  567. // link.click();
  568. // 創建一個&lt;a&gt;元素
  569. const link = document.createElement('a');
  570. // 將 Canvas 轉換為 Data URL
  571. link.href = canvas.toDataURL('image/png');
  572. // 設置下載文件名
  573. link.download = 'chart.png';
  574. // 模擬點擊下載
  575. link.click();
  576. });
  577. }, 1000); // 等待 1 秒钟
  578. });
  579. var pieChartColors = [
  580. 'rgb(171, 51, 49)',
  581. 'rgb(34, 83, 149)',
  582. 'rgb(79, 148, 65)',
  583. 'rgb(217, 195, 105)',
  584. 'rgb(142, 124, 180)',
  585. 'rgb(211, 183, 144)',
  586. 'rgb(83, 84, 84)',
  587. 'rgb(229, 147, 152)'
  588. ];
  589. function createChartDoughnut2(data, labels) {
  590. const chartData = {
  591. type: 'outlabeledPie',
  592. data: {
  593. labels: labels,
  594. datasets: [
  595. {
  596. data: data,
  597. borderWidth: borderWidthValue,
  598. fill: false,
  599. backgroundColor: pieChartColors,
  600. },
  601. ],
  602. },
  603. options: {
  604. plugins: {
  605. legend: false,
  606. outlabels: {
  607. text: '%l %p',
  608. color: 'white',
  609. stretch: 35,
  610. font: {
  611. resizable: true,
  612. family: 'Arial',
  613. size: 48,
  614. weight: 'bold',
  615. style: 'italic',
  616. },
  617. },
  618. },
  619. },
  620. };
  621. const devicePixelRatio = 4;
  622. var chartUrl = `https://quickchart.io/chart?c=${encodeURIComponent(JSON.stringify(chartData))}&devicePixelRatio=${devicePixelRatio}&f=png&fontsize=20`;
  623. // 获取目标 div 元素
  624. const targetDiv = document.getElementById('data_chartJs_box');
  625. // 创建一个 img 元素来显示图表
  626. const chartImg = document.createElement('img');
  627. chartImg.src = chartUrl;
  628. chartImg.classList.add('outlabeled_img');
  629. // 清空目标 div 元素
  630. targetDiv.innerHTML = '';
  631. // 将图表 img 元素插入到目标 div 中
  632. targetDiv.appendChild(chartImg);
  633. console.log(chart_bgimg_url);
  634. bgImgelement.style.backgroundImage = chart_bgimg_url;
  635. chartWhitelement.style.background = "rgba(255,255,255,0.5)"
  636. }
  637. // 版型二源餅圖
  638. // // 创建 Chart.js 图表
  639. function createChartDoughnut(chartType, data, labels) {
  640. $('#textToChart').show();
  641. canvasPng.style.maxWidth = '450px';
  642. canvasPng.style.maxHeight = '450px';
  643. var windowWidth = window.innerWidth || document.documentElement.clientWidth;
  644. var canvasWidth = Math.min(500, windowWidth); // 限制最大宽度为 500px
  645. canvasPng.style.width = canvasWidth + 'px'; // 设置 canvas 宽度
  646. canvasPng.style.marginLeft = 'auto'; // 左外边距自动计算
  647. canvasPng.style.marginRight = 'auto'; // 右外边距自动计算
  648. var ctx = document.getElementById("textToChart").getContext('2d');
  649. myChart = new Chart(ctx, {
  650. type: chartType,
  651. data: {
  652. labels: labels,
  653. datasets: [{
  654. strokeColor: "rgba(220,220,220,1)",
  655. StrokeWidth: 5,
  656. data: data,
  657. borderWidth: borderWidthValue,
  658. pointRadius: 0,
  659. pointBorderColor: '#fff',
  660. pointBorderWidth: 3,
  661. pointHoverRadius: 0,
  662. fill: false,
  663. backgroundColor: pieChartColors,
  664. // barPercentage: 0.5,
  665. // categoryPercentage: 0.5
  666. }]
  667. },
  668. options: {
  669. // responsive: true, // 啟用響應式
  670. maintainAspectRatio: true,
  671. responsive: true,
  672. aspectRatio: 1,
  673. plugins: {
  674. legend: {
  675. display: false,
  676. },
  677. datalabels: {
  678. color: '#fff', // 数据标签的颜色
  679. anchor: 'end', // 数据标签的位置
  680. align: 'start', // 数据标签的对齐方式
  681. font: {
  682. size: 14, // 数据标签的字体大小
  683. },
  684. }
  685. },
  686. scales: {
  687. x: {
  688. display: false, // 显示 x 轴
  689. grid: {
  690. display: false,
  691. lineWidth: 5,
  692. color: '#584B3D'
  693. },
  694. ticks: {
  695. textStrokeColor: '#fff',
  696. textStrokeWidth: 5,
  697. font: {
  698. display: false,
  699. family: 'Arial', // 设置字体
  700. size: XfontSizeValue, // 设置字体大小
  701. weight: 'bold', // 设置字体粗细
  702. fontColor: 'rgba(255,255,255,0.8)', // X-axis font color
  703. shadowColor: 'rgba(0, 0, 0, 0.5)', // Shadow color
  704. shadowBlur: 10, // Shadow blur level
  705. shadowOffsetX: 5, // Horizontal shadow offset
  706. shadowOffsetY: 5
  707. },
  708. },
  709. },
  710. y: {
  711. display: false,
  712. beginAtZero: false,
  713. grid: {
  714. display: false,
  715. lineWidth: 5,
  716. color: '#584B3D'
  717. },
  718. ticks: {
  719. textStrokeColor: '#fff',
  720. textStrokeWidth: 5,
  721. font: {
  722. family: 'Arial', // 設置字體
  723. size: XfontSizeValue, // 設置字體大小
  724. weight: 'bold', // 設置字體粗細
  725. color: 'rgba(255,255,255,0.8)', // Y-axis 字體顏色
  726. shadowColor: 'rgba(0, 0, 0, 0.5)', // 陰影顏色
  727. shadowBlur: 10, // 陰影模糊級別
  728. shadowOffsetX: 5, // 水平陰影偏移
  729. shadowOffsetY: 5 // 垂直陰影偏移
  730. },
  731. }
  732. }
  733. },
  734. layout: {
  735. padding: {
  736. left: 50, // 调整图表左边距
  737. right: 50, // 调整图表右边距
  738. top: 10,
  739. bottom: 10,
  740. }
  741. },
  742. },
  743. });
  744. console.log(chart_bgimg_url);
  745. bgImgelement.style.backgroundImage = chart_bgimg_url;
  746. chartWhitelement.style.background = "rgba(255,255,255,0.5)"
  747. }
  748. var chartJsBox = document.getElementById('data_chartJs_box');
  749. function createTable(dataArray, unit, Label_dependent_variable, Label_independent_variable,) {
  750. $('#chartdiv').hide();
  751. $('#textToChart').hide();
  752. chartTitle.style.padding = "0px 0px 0px 30px";
  753. bgImgelement.style.paddingTop = "10px";
  754. var table = document.createElement('table');
  755. table.classList.add('table', 'table_template', 'dynamic-table'); // 添加 Bootstrap 的 table 样式,如果你在使用 Bootstrap
  756. // 创建表头
  757. var thead = table.createTHead();
  758. var headerRow = thead.insertRow();
  759. // Object.keys(dataArray[0]).forEach(function (key) {
  760. // var header = headerRow.insertCell();
  761. // header.textContent = key;
  762. // });
  763. var yearHeader = headerRow.insertCell();
  764. yearHeader.textContent = Label_independent_variable;
  765. var avgPriceHeader = headerRow.insertCell();
  766. avgPriceHeader.textContent = Label_dependent_variable;
  767. // 创建表格主体
  768. var tbody = table.createTBody();
  769. dataArray.forEach(function (item) {
  770. console.log(item)
  771. var row = tbody.insertRow();
  772. // var cell1 = row.insertCell();
  773. // cell1.textContent = item.year;
  774. // cell1.classList.add('year-class'); // 为年份单元格添加类
  775. // var cell2 = row.insertCell();
  776. Object.keys(item).forEach(function (key, index) {
  777. var cell = row.insertCell();
  778. if (index === 0) { // If it's the first cell, add 'year-class'
  779. cell.textContent = item[key];
  780. cell.classList.add('year-class');
  781. } else { // Otherwise, add 'average-class'
  782. if (key === 'Average_Close') {
  783. // cell.textContent = item[key].toFixed(2) + unit;
  784. cell.innerHTML = item[key].toFixed(2) + '<span class="unit_table">' + unit + '</span>';
  785. } else {
  786. // cell.textContent = item[key];
  787. // cell.textContent = item[key].toFixed(2) + unit;
  788. cell.innerHTML = item[key].toFixed(2) + '<span class="unit_table">' + unit + '</span>';
  789. }
  790. cell.classList.add('average-class');
  791. }
  792. });
  793. // console.log(item.avg_price.toFixed(2))
  794. // cell.textContent = item[key].toFixed(2) + unit;
  795. // cell2.classList.add('average-class'); // 为年份单元格添加类
  796. });
  797. // 获取包含表格的 div 元素
  798. bgImgelement.style.backgroundImage = chart_bgimg_url;
  799. img_box.style.bottom = '60px';
  800. img_box.style.right = '5px';
  801. document.getElementById('img_box_url').style.width = "180px";
  802. // chartWhitelement.style.background = "rgba(255,255,255,0.5)"
  803. // 将表格添加到指定的 div 元素中
  804. chartJsBox.appendChild(table);
  805. unit_table_value = document.querySelectorAll('.unit_table');
  806. downloadButton.style.display = "inline-block";
  807. }
  808. function getDatalabelsConfig(dataLength) {
  809. if (dataLength < 10) {
  810. return {
  811. formatter: function (value, context) {
  812. return value + ' unit'; // Add unit if data length is less than 10
  813. },
  814. textStrokeColor: '#fff',
  815. textStrokeWidth: 5,
  816. color: '#584B3D',
  817. font: {
  818. size: YfontSizeValue,
  819. },
  820. anchor: 'end',
  821. align: 'end',
  822. };
  823. } else {
  824. return null; // No datalabels if data length is 10 or more
  825. }
  826. }
  827. // 版型一折線圖
  828. // // 创建 Chart.js 图表
  829. function createChart(chartType, data, labels) {
  830. $('#textToChart').show();
  831. canvasPng.style.maxWidth = '';
  832. canvasPng.style.maxHeight = '';
  833. const datalabelsConfig = data.length <= 10 ? {
  834. formatter: function (value, context) {
  835. return value;
  836. },
  837. textStrokeColor: '#fff',
  838. textStrokeWidth: 5,
  839. color: '#584B3D',
  840. font: {
  841. size: YfontSizeValue,
  842. },
  843. anchor: 'end',
  844. align: 'right'
  845. } : null;
  846. ctx = document.getElementById("textToChart");
  847. myChart = new Chart(ctx, {
  848. type: chartType,
  849. data: {
  850. labels: labels,
  851. datasets: [{
  852. strokeColor: "rgba(220,220,220,1)",
  853. StrokeWidth: 5,
  854. data: data,
  855. borderWidth: borderWidthValue,
  856. pointRadius: 0,
  857. pointBorderColor: '#fff',
  858. pointBorderWidth: 3,
  859. pointHoverRadius: 0,
  860. fill: false,
  861. backgroundColor: chartColor,
  862. borderColor: chartColor,
  863. // barPercentage: 0.5,
  864. // categoryPercentage: 0.5
  865. }]
  866. },
  867. options: {
  868. // responsive: true, // 啟用響應式
  869. maintainAspectRatio: false,
  870. plugins: {
  871. chart3d: {
  872. enabled: true, // 啟用 3D 插件
  873. alpha: 25, // 圖表繞 x 軸的旋轉角度
  874. beta: 25, // 圖表繞 y 軸的旋轉角度
  875. depth: 15 // 圖表的深度
  876. },
  877. datalabels: datalabelsConfig,
  878. // datalabels: {
  879. // formatter: function (value, context) {
  880. // // 添加单位
  881. // return value;
  882. // },
  883. // textStrokeColor: '#fff',
  884. // textStrokeWidth: 5,
  885. // color: '#584B3D',
  886. // font: {
  887. // size: YfontSizeValue,
  888. // },
  889. // anchor: 'end',
  890. // align: 'end',
  891. // },
  892. // datalabels: null,
  893. // datalabels: data.length <= 10 ? {
  894. // formatter: function (value, context) {
  895. // // 添加单位
  896. // return value + ' ' + unit;
  897. // },
  898. // textStrokeColor: '#fff',
  899. // textStrokeWidth: 5,
  900. // color: '#584B3D',
  901. // font: {
  902. // size: YfontSizeValue,
  903. // },
  904. // anchor: 'end',
  905. // align: 'end',
  906. // } : null,
  907. customLabels: null,
  908. legend: {
  909. display: false,
  910. },
  911. // subtitle: {
  912. // display: true,
  913. // align: 'left',
  914. // position: 'top',
  915. // text: 'Custom Chart Subtitle'
  916. // },
  917. // afterDatasetsDraw(chart) {
  918. // var ctx = chart.ctx;
  919. // var xAxis = chart.scales.x;
  920. // var yAxis = chart.scales.y;
  921. // var dataj = myChart.data.datasets[0].data;
  922. // console.log('after', dataj)
  923. // ctx.save();
  924. // ctx.strokeStyle = '#000'; // 虚线颜色
  925. // ctx.lineWidth = 1; // 虚线宽度
  926. // ctx.setLineDash([5, 5]); // 设置虚线样式,[虚线段长度, 间隔长度]
  927. // dataj.forEach(function (value, index) {
  928. // var xPos = xAxis.getPixelForValue(labels[index]); // 获取 x 轴位置
  929. // var yPos = yAxis.getPixelForValue(value); // 获取 y 轴位置
  930. // // console.log(xPos)
  931. // // 绘制虚线
  932. // // ctx.beginPath();
  933. // // ctx.moveTo(xPos, yPos);
  934. // // ctx.lineTo(xPos, xAxis.bottom);
  935. // // ctx.stroke();
  936. // var xLineEnd = Math.min(yPos, yAxis.bottom);
  937. // // console.log('第' + index + '條線', xPos, yPos, 'xLineEnd', xLineEnd, 'yAxis.getPixelForValue(value)', yAxis.getPixelForValue(value));
  938. // // console.log('yAxis.getPixelForValue(value)', yAxis.getPixelForValue(value))
  939. // // 绘制虚线
  940. // ctx.beginPath();
  941. // ctx.moveTo(xPos, yAxis.getPixelForValue(value));
  942. // ctx.lineTo(xPos, xAxis.top);
  943. // ctx.stroke();
  944. // // 添加日期标签
  945. // ctx.fillStyle = '#000'; // 文字颜色
  946. // ctx.textAlign = 'center';
  947. // // ctx.fillText(labels[index], xPos, yAxis.bottom + 20); // 将日期标签绘制在虚线下方
  948. // });
  949. // ctx.restore();
  950. // }
  951. },
  952. scales: {
  953. x: {
  954. display: displayXaxes, // 显示 x 轴
  955. grid: {
  956. display: false,
  957. lineWidth: 5,
  958. color: '#584B3D'
  959. },
  960. ticks: {
  961. textStrokeColor: '#fff',
  962. textStrokeWidth: 5,
  963. font: {
  964. display: false,
  965. family: 'Arial', // 设置字体
  966. size: XfontSizeValue, // 设置字体大小
  967. weight: 'bold', // 设置字体粗细
  968. fontColor: 'rgba(255,255,255,0.8)', // X-axis font color
  969. shadowColor: 'rgba(0, 0, 0, 0.5)', // Shadow color
  970. shadowBlur: 10, // Shadow blur level
  971. shadowOffsetX: 5, // Horizontal shadow offset
  972. shadowOffsetY: 5
  973. },
  974. },
  975. },
  976. y: {
  977. display: true,
  978. beginAtZero: false,
  979. grid: {
  980. grid: {
  981. display: true, // 显示 y 轴网格线
  982. lineWidth: 1, // 网格线宽度
  983. color: '#C0C5CC' // 网格线颜色
  984. },
  985. },
  986. ticks: {
  987. textStrokeColor: '#fff',
  988. textStrokeWidth: 5,
  989. font: {
  990. family: 'Arial', // 設置字體
  991. size: XfontSizeValue, // 設置字體大小
  992. weight: 'bold', // 設置字體粗細
  993. color: 'rgba(255,255,255,0.8)', // Y-axis 字體顏色
  994. shadowColor: 'rgba(0, 0, 0, 0.5)', // 陰影顏色
  995. shadowBlur: 10, // 陰影模糊級別
  996. shadowOffsetX: 5, // 水平陰影偏移
  997. shadowOffsetY: 5 // 垂直陰影偏移
  998. },
  999. }
  1000. }
  1001. },
  1002. layout: {
  1003. padding: {
  1004. left: 50, // 调整图表左边距
  1005. right: 50, // 调整图表右边距
  1006. top: 40,
  1007. bottom: 10,
  1008. }
  1009. },
  1010. },
  1011. });
  1012. // 注册 afterDraw 事件
  1013. // Chart.register({
  1014. // id: 'afterDraw',
  1015. // afterDraw: function (chart) {
  1016. // // console.log('處發', chart)
  1017. // // 在这里添加你的绘制代码
  1018. // var ctx = chart.ctx;
  1019. // var xAxis = chart.scales.x;
  1020. // var yAxis = chart.scales.y;
  1021. // var dataj = myChart.data.datasets[0].data;
  1022. // console.log('after', dataj)
  1023. // ctx.save();
  1024. // ctx.strokeStyle = '#000'; // 虚线颜色
  1025. // ctx.lineWidth = 1; // 虚线宽度
  1026. // ctx.setLineDash([5, 5]); // 设置虚线样式,[虚线段长度, 间隔长度]
  1027. // dataj.forEach(function (value, index) {
  1028. // var xPos = xAxis.getPixelForValue(labels[index]); // 获取 x 轴位置
  1029. // var yPos = yAxis.getPixelForValue(value); // 获取 y 轴位置
  1030. // // console.log(xPos)
  1031. // // 绘制虚线
  1032. // // ctx.beginPath();
  1033. // // ctx.moveTo(xPos, yPos);
  1034. // // ctx.lineTo(xPos, xAxis.bottom);
  1035. // // ctx.stroke();
  1036. // var xLineEnd = Math.min(yPos, yAxis.bottom);
  1037. // // console.log('第' + index + '條線', xPos, yPos, 'xLineEnd', xLineEnd, 'yAxis.getPixelForValue(value)', yAxis.getPixelForValue(value));
  1038. // // console.log('yAxis.getPixelForValue(value)', yAxis.getPixelForValue(value))
  1039. // // 绘制虚线
  1040. // ctx.beginPath();
  1041. // ctx.moveTo(xPos, yAxis.getPixelForValue(value));
  1042. // ctx.lineTo(xPos, xAxis.top);
  1043. // ctx.stroke();
  1044. // // 添加日期标签
  1045. // ctx.fillStyle = '#000'; // 文字颜色
  1046. // ctx.textAlign = 'center';
  1047. // // ctx.fillText(labels[index], xPos, yAxis.bottom + 20); // 将日期标签绘制在虚线下方
  1048. // });
  1049. // ctx.restore();
  1050. // }
  1051. // });
  1052. console.log(chart_bgimg_url);
  1053. bgImgelement.style.backgroundImage = chart_bgimg_url;
  1054. chartWhitelement.style.background = "rgba(255,255,255,0.5)";
  1055. downloadButton.style.display = "inline-block";
  1056. }
  1057. // createChart(chartType);
  1058. // createChart(chartType)
  1059. const ChartOptions = document.querySelectorAll('input[name="ChartOptions"]');
  1060. ChartOptions.forEach(button => {
  1061. button.addEventListener('click', function () {
  1062. // console.log(this.value);
  1063. chartType = this.value;
  1064. console.log(chartType);
  1065. if (myChart !== null) {
  1066. myChart.destroy();
  1067. data = [];
  1068. labels = [];
  1069. }
  1070. if (chartType === 'line') {
  1071. $('#chartdiv').hide();
  1072. generateChart(dataArray);
  1073. } else {
  1074. $('#textToChart').hide();
  1075. extractAndGenerateChart(dataArray);
  1076. }
  1077. // createChart(chartType, data, labels);
  1078. });
  1079. });
  1080. // 表格字體
  1081. var fontSizeInput = document.getElementById('table_fontSize');
  1082. // 添加事件监听器
  1083. fontSizeInput.addEventListener('input', function () {
  1084. // 获取输入框的值
  1085. var fontSize = fontSizeInput.value;
  1086. // 获取动态创建的表格元素
  1087. var dynamicTable = document.querySelector('.dynamic-table');
  1088. // 如果表格存在,则调整其字体大小
  1089. if (dynamicTable) {
  1090. dynamicTable.style.fontSize = fontSize + 'px';
  1091. }
  1092. });
  1093. // 是否顯示point
  1094. var togglePoints = document.getElementById('togglePoints');
  1095. togglePoints.addEventListener('change', function () {
  1096. console.log('checked')
  1097. if (this.checked) {
  1098. myChart.data.datasets[0].pointRadius = 5;
  1099. myChart.data.datasets[0].pointHoverRadius = 8;
  1100. } else {
  1101. myChart.data.datasets[0].pointRadius = 0;
  1102. myChart.data.datasets[0].pointHoverRadius = 0;
  1103. }
  1104. myChart.update();
  1105. });
  1106. // 單位
  1107. // =========================
  1108. var unitInput = document.getElementById('unit_data');
  1109. var unit_value = document.querySelector('.unit');
  1110. // console.log('單位', unitInput)
  1111. unitInput.addEventListener('input', function () {
  1112. // unitInput.value = unit_value.textContent;
  1113. if (chartType === 'table') {
  1114. // unit_table_value.textContent = this.value;
  1115. unit_table_value.forEach(span => {
  1116. span.textContent = this.value;
  1117. });
  1118. } else {
  1119. unit_value.textContent = '單位:' + this.value
  1120. }
  1121. });
  1122. // ==========================
  1123. // y軸字體大小-折線圖
  1124. // ==========================
  1125. var YfontSize = document.getElementById('YfontSize');
  1126. YfontSize.addEventListener('input', function () {
  1127. YfontSizeValue = YfontSize.value;
  1128. if (myChart) {
  1129. myChart.destroy();
  1130. }
  1131. createChart(chartType, data, labels);
  1132. });
  1133. // ==========================
  1134. // x軸字體大小-折線圖
  1135. // ==========================
  1136. var XfontSize = document.getElementById('XfontSize');
  1137. XfontSize.addEventListener('input', function () {
  1138. XfontSizeValue = XfontSize.value;
  1139. console.log(XfontSizeValue)
  1140. if (myChart) {
  1141. myChart.destroy();
  1142. }
  1143. createChart(chartType, data, labels);
  1144. });
  1145. // ==========================
  1146. // x軸字體大小-柱狀圖
  1147. // ==========================
  1148. var XfontSizeBar = document.getElementById('XfontSizeBar');
  1149. XfontSizeBar.addEventListener('input', function () {
  1150. extractAndGenerateChart(dataArray);
  1151. });
  1152. // ==========================
  1153. // y軸字體大小-柱狀圖
  1154. // ==========================
  1155. var YfontSizeBar = document.getElementById('YfontSizeBar');
  1156. YfontSizeBar.addEventListener('input', function () {
  1157. extractAndGenerateChart(dataArray);
  1158. });
  1159. // ==========================
  1160. // 線條顏色-柱狀圖
  1161. // =========================
  1162. const colorInputBar = document.getElementById('borderColorInputBar');
  1163. // 添加事件监听器,当颜色选择发生变化时触发
  1164. colorInputBar.addEventListener('input', function () {
  1165. extractAndGenerateChart(dataArray);
  1166. });
  1167. // =========================
  1168. // 線條粗細
  1169. // =========================
  1170. var rangeInput = document.getElementById('borderWidthRange');
  1171. var rangeInputSpan = document.getElementById('borderWidthRangeValue');
  1172. var borderWidthValue;
  1173. rangeInputSpan.textContent = rangeInput.value;
  1174. // 添加事件监听器,当滑动条的值发生改变时更新显示的值
  1175. rangeInput.addEventListener('input', function () {
  1176. // 获取滑动条的当前值
  1177. borderWidthValue = rangeInput.value;
  1178. console.log(borderWidthValue);
  1179. rangeInputSpan.textContent = borderWidthValue;
  1180. if (myChart) {
  1181. myChart.destroy();
  1182. }
  1183. createChart(chartType, data, labels);
  1184. // myChart.data.datasets[0].borderWidth = borderWidthValue;
  1185. });
  1186. // =========================
  1187. // 線條顏色-折線圖
  1188. // =========================
  1189. const colorInput = document.getElementById('borderColorInput');
  1190. // 添加事件监听器,当颜色选择发生变化时触发
  1191. colorInput.addEventListener('input', function () {
  1192. // 获取当前选择的颜色值
  1193. chartColor = colorInput.value;
  1194. if (myChart) {
  1195. myChart.destroy();
  1196. }
  1197. console.log(chartColor);
  1198. createChart(chartType, data, labels);
  1199. });
  1200. // =========================
  1201. // 模板樣式
  1202. // =========================
  1203. // JavaScript
  1204. document.addEventListener("DOMContentLoaded", function () {
  1205. // 獲取所有帶有 templateImg class 的圖像元素
  1206. var templateImgs = document.querySelectorAll('.templateImg');
  1207. // 為每個圖像元素添加點擊事件監聽器
  1208. templateImgs.forEach(function (img) {
  1209. img.addEventListener('click', function () {
  1210. // 在點擊時印出圖像元素的 value 屬性值
  1211. console.log(this.getAttribute('value'));
  1212. });
  1213. });
  1214. });
  1215. // =========================
  1216. var bgImgelement = document.getElementById('data_chart_box');
  1217. var chartWhitelement = document.getElementById('data_chartJs_box');
  1218. // 背景樣式
  1219. // =========================
  1220. // JavaScript
  1221. document.addEventListener("DOMContentLoaded", function () {
  1222. // 獲取所有帶有 templateImg class 的圖像元素
  1223. var bgImgs = document.querySelectorAll('.bgImg');
  1224. // 為每個圖像元素添加點擊事件監聽器
  1225. bgImgs.forEach(function (img) {
  1226. img.addEventListener('click', function () {
  1227. // 在點擊時印出圖像元素的 value 屬性值
  1228. console.log(this.getAttribute('value'));
  1229. var bgImgUrl = this.getAttribute('value');
  1230. chart_bgimg_url = 'url(' + bgImgUrl + ')';
  1231. if (bgImgUrl === './img/bg07.webp') {
  1232. chartTitle.style.color = "#ffff";
  1233. } else {
  1234. chartTitle.style.color = "#1c2d6d";
  1235. }
  1236. bgImgelement.style.backgroundImage = chart_bgimg_url;
  1237. // bgImgelement.style.backgroundSize = 'cover'; // 調整背景圖片大小
  1238. // bgImgelement.style.backgroundPosition = 'center'; // 調整背景圖片位置
  1239. // bgImgelement.style.backgroundRepeat = 'no-repeat'; // 調整背景圖片重複
  1240. });
  1241. });
  1242. });
  1243. // =========================
  1244. const radioButtons = document.querySelectorAll('input[name="inlineRadioOptions"]');
  1245. var chartTitle = document.querySelector('.chart_title');
  1246. radioButtons.forEach(button => {
  1247. button.addEventListener('click', function () {
  1248. if (this.value === '0') {
  1249. chartTitle.style.textAlign = 'left';
  1250. } else if (this.value === '1') {
  1251. chartTitle.style.textAlign = 'center';
  1252. } else if (this.value === '2') {
  1253. chartTitle.style.textAlign = 'right';
  1254. }
  1255. });
  1256. });
  1257. // 圖表標題
  1258. var keywordInput = document.getElementById('title_data');
  1259. // 初始时将输入框的值设置为标题的文本内容
  1260. keywordInput.value = chartTitle.textContent;
  1261. // 监听输入框的输入事件,实现内容同步更新
  1262. keywordInput.addEventListener('input', function () {
  1263. chartTitle.textContent = this.value;
  1264. });
  1265. // 標題字體大小
  1266. // ==========================
  1267. var TitlefontSize = document.getElementById('TitlefontSize');
  1268. TitlefontSize.addEventListener('input', function () {
  1269. var TitlefontSizeValue = TitlefontSize.value;
  1270. chartTitle.style.fontSize = TitlefontSizeValue + 'px';;
  1271. });
  1272. // 標題字體顏色
  1273. // ==========================
  1274. let labelDependent = ""; // 圖表左側 Label
  1275. function get_data(input_text_value) {
  1276. inputField.value = "";
  1277. apiLoading();
  1278. var existingTable = chartJsBox.querySelector('table');
  1279. downloadButton.style.display = "none";
  1280. if (chartDiv.childElementCount != 0) {
  1281. data = [];
  1282. labels = [];
  1283. console.log('已存在')
  1284. chartTitle.textContent = "";
  1285. unit_value.textContent = "";
  1286. bgImgelement.style.backgroundImage = "";
  1287. chartWhitelement.style.background = "";
  1288. document.getElementById('img_box_url').src = "";
  1289. }
  1290. if (existingTable) {
  1291. unit_value.textContent = "";
  1292. chartJsBox.removeChild(existingTable);
  1293. chartTitle.textContent = "";
  1294. bgImgelement.style.backgroundImage = "";
  1295. chartWhitelement.style.background = "";
  1296. document.getElementById('img_box_url').src = "";
  1297. }
  1298. if (myChart) {
  1299. unit_value.textContent = "";
  1300. data = [];
  1301. labels = [];
  1302. chartTitle.textContent = "";
  1303. bgImgelement.style.backgroundImage = "";
  1304. chartWhitelement.style.background = "";
  1305. myChart.destroy();
  1306. document.getElementById('img_box_url').src = "";
  1307. }
  1308. axios.get('https://cmm.ai:8080/answer_with_token?token=' + accessToken + '&question=' + input_text_value)
  1309. .then(response => {
  1310. apiHideLoading();
  1311. console.log(response);
  1312. if (response.data.data == "Failed to generate chart!") {
  1313. alert('無法生成圖表')
  1314. return
  1315. } else {
  1316. var chart_info = response.data.chart_info.Title;
  1317. chartType = response.data.chart_info.Chart_type;
  1318. var finance_img_url = response.data.imageUrl_info.imageUrl;
  1319. if (response.data.imageUrl_info != null) {
  1320. console.log(finance_img_url);
  1321. document.getElementById('img_box_url').src = finance_img_url;
  1322. }
  1323. keywordInput.value = chart_info;
  1324. chartTitle.textContent = chart_info;
  1325. unit = response.data.chart_info.Unit_of_dependent_variable;
  1326. var Label_dependent_variable = response.data.chart_info.Label_dependent_variable;
  1327. var Label_independent_variable = response.data.chart_info.Label_independent_variable;
  1328. unit_data.value = response.data.chart_info.Unit_of_dependent_variable;
  1329. if (response.data.chart_info.Unit_of_dependent_variable == "") {
  1330. unit_value.textContent = ""
  1331. } else {
  1332. unit_value.textContent = '單位:' + response.data.chart_info.Unit_of_dependent_variable;
  1333. }
  1334. dataArray = response.data.data;
  1335. if (chartType === "table") {
  1336. unit_value.textContent = "";
  1337. createTable(dataArray, unit, Label_dependent_variable, Label_independent_variable);
  1338. // document.getElementById('img_box_url').src = "";
  1339. } else if (chartType === "bar") {
  1340. console.log('圖表類型bar')
  1341. $('#textToChart').hide();
  1342. extractAndGenerateChart(dataArray);
  1343. } else if (chartType === "doughnut") {
  1344. unit_value.textContent = "";
  1345. $('#textToChart').hide();
  1346. generatePieChart(dataArray)
  1347. } else {
  1348. $('#chartdiv').hide();
  1349. generateChart(dataArray);
  1350. }
  1351. // }
  1352. // 在這裡處理成功獲取 JSON 的情況
  1353. // console.log(response);
  1354. // switch (chartType) {
  1355. // case "line":
  1356. // document.getElementById("inlineRadio4").checked = true; // 折线图
  1357. // break;
  1358. // case "bar":
  1359. // document.getElementById("inlineRadio5").checked = true; // 柱状图
  1360. // labelDependent = response.data.chart_info.Label_dependent_variable;
  1361. // break;
  1362. // case "pie":
  1363. // document.getElementById("inlineRadio6").checked = true; // 圆饼图
  1364. // break;
  1365. // case "table":
  1366. // document.getElementById("inlineRadio7").checked = true; // 表格
  1367. // break;
  1368. // default:
  1369. // // 默认情况
  1370. }
  1371. // generateChart(dataArray);
  1372. })
  1373. .catch(error => {
  1374. apiHideLoading();
  1375. // 在這裡處理請求失敗的情況
  1376. console.error('發生錯誤:', error);
  1377. });
  1378. }
  1379. $(document).ready(function () {
  1380. $('#dataTable').DataTable();
  1381. });
  1382. function resizeChart() {
  1383. if (myChart) {
  1384. myChart.resize();
  1385. }
  1386. }
  1387. document.addEventListener('visibilitychange', function () {
  1388. console.log('Visibility changed:', document.visibilityState);
  1389. if (document.visibilityState === 'visible') {
  1390. resizeChart();
  1391. }
  1392. });
  1393. // 监听窗口resize事件
  1394. window.addEventListener('resize', resizeChart);
  1395. var setting_button = document.getElementById('chart_seeting_button');
  1396. var closeButton = document.getElementById('style_setting_close');
  1397. var closeButton_table = document.getElementById('style_setting_close_table');
  1398. // var borderSetting = document.getElementById('borderSetting');
  1399. var lineChartSetting = document.getElementById('lineChartSetting');
  1400. var barChartSetting = document.getElementById('barChartSetting');
  1401. var table_setting = document.getElementById('table_setting');
  1402. var chart_category = document.getElementById('chart_category');
  1403. // 获取 chartDiv 元素
  1404. setting_button.addEventListener('click', () => {
  1405. console.log('setting_button')
  1406. if (myChart === null && !chartJsBox.querySelector('table') && chartDiv.childElementCount === 0) {
  1407. alert('請先生成圖表');
  1408. return
  1409. }
  1410. if (chartType === 'table') {
  1411. console.log('表格');
  1412. sidebar.classList.toggle('show');
  1413. sidebar.classList.toggle('hidden');
  1414. barChartSetting.style.display = 'none';
  1415. lineChartSetting.style.display = 'none';
  1416. table_setting.style.display = 'block';
  1417. chart_category.style.display = 'none';
  1418. } else if (chartType === "bar") {
  1419. console.log('柱狀圖')
  1420. sidebar.classList.toggle('show');
  1421. sidebar.classList.toggle('hidden');
  1422. barChartSetting.style.display = 'block';
  1423. lineChartSetting.style.display = 'none';
  1424. table_setting.style.display = 'none';
  1425. } else if (chartType === "doughnut") {
  1426. console.log('快捷功能圓餅圖')
  1427. sidebar.classList.toggle('show');
  1428. sidebar.classList.toggle('hidden');
  1429. barChartSetting.style.display = 'none';
  1430. lineChartSetting.style.display = 'none';
  1431. table_setting.style.display = 'none';
  1432. chart_category.style.display = 'none';
  1433. } else {
  1434. sidebar.classList.toggle('show');
  1435. sidebar.classList.toggle('hidden');
  1436. table_setting.style.display = 'none';
  1437. barChartSetting.style.display = 'none';
  1438. lineChartSetting.style.display = 'block';
  1439. }
  1440. });
  1441. closeButton.addEventListener('click', () => {
  1442. sidebar.classList.remove('show');
  1443. sidebar.classList.add('hidden');
  1444. });
  1445. const finance_options = [
  1446. { name: "原油油桶", imageUrl: "./img/finance/01.webp" },
  1447. { name: "黃金", imageUrl: "./img/finance/02.webp" },
  1448. { name: "房屋", imageUrl: "./img/finance/03.webp" },
  1449. { name: "車", imageUrl: "./img/finance/04.webp" },
  1450. { name: "股市", imageUrl: "./img/finance/05.webp" },
  1451. { name: "晶圓", imageUrl: "./img/finance/06.webp" },
  1452. { name: "TSMC 台積電", imageUrl: "./img/finance/07.webp" },
  1453. { name: "台幣", imageUrl: "./img/finance/08.webp" },
  1454. { name: "美金", imageUrl: "./img/finance/09.webp" },
  1455. { name: "購物車", imageUrl: "./img/finance/10.webp" },
  1456. { name: "美中貿易", imageUrl: "./img/finance/11.webp" },
  1457. { name: "世界地圖", imageUrl: "./img/finance/12.webp" },
  1458. { name: "小麥", imageUrl: "./img/finance/13.webp" },
  1459. { name: "玉米", imageUrl: "./img/finance/14.webp" },
  1460. { name: "智慧產線", imageUrl: "./img/finance/15.webp" }
  1461. ];
  1462. const selectOptions = document.getElementById('finance_options');
  1463. const selectOptions_table = document.getElementById('finance_options_table');
  1464. finance_options.forEach((option, index) => {
  1465. const optionElement = document.createElement('option');
  1466. optionElement.value = index + 1; // 值从 1 开始
  1467. optionElement.textContent = option.name;
  1468. optionElement.setAttribute('data-image-url', option.imageUrl); // 存储图片 URL
  1469. selectOptions.appendChild(optionElement);
  1470. });
  1471. selectOptions.addEventListener('change', function () {
  1472. const selectedOption = selectOptions.options[selectOptions.selectedIndex];
  1473. const imageUrl = selectedOption.getAttribute('data-image-url');
  1474. document.getElementById('img_box_url').src = imageUrl;
  1475. });
  1476. // finance_options.forEach((option, index) => {
  1477. // const optionElement = document.createElement('option');
  1478. // optionElement.value = index + 1; // 值从 1 开始
  1479. // optionElement.textContent = option.name;
  1480. // optionElement.setAttribute('data-image-url', option.imageUrl); // 存储图片 URL
  1481. // selectOptions_table.appendChild(optionElement);
  1482. // });
  1483. // selectOptions_table.addEventListener('change', function () {
  1484. // const selectedOption = selectOptions_table.options[selectOptions_table.selectedIndex];
  1485. // const imageUrl = selectedOption.getAttribute('data-image-url');
  1486. // document.getElementById('img_box_url').src = imageUrl;
  1487. // });
  1488. document.querySelectorAll('input[name="ChartOptions"]').forEach(function (radio) {
  1489. radio.addEventListener('change', function () {
  1490. // 檢查哪個單選按鈕被選中
  1491. if (this.value === 'line') {
  1492. // 如果選擇了折線圖,執行相應的操作
  1493. console.log("選擇了折線圖");
  1494. // 在這裡執行顯示折線圖的相關代碼
  1495. } else if (this.value === 'doughnut') {
  1496. // 如果選擇了柱狀圖,執行相應的操作
  1497. console.log("選擇了柱狀圖");
  1498. // 在這裡執行顯示柱狀圖的相關代碼
  1499. }
  1500. });
  1501. });
  1502. function tokencheck() {
  1503. if (!localStorage.getItem("access_token")) {
  1504. window.location.href = "./login.html";
  1505. } else {
  1506. console.log("存在");
  1507. }
  1508. }
  1509. tokencheck();
  1510. function logout() {
  1511. localStorage.removeItem("access_token");
  1512. }
  1513. $(document).on("click", "#logout", function (event) {
  1514. alert("登出成功");
  1515. logout();
  1516. location.reload();
  1517. });
  1518. // speech_to_text
  1519. var closeRecord = document.getElementById('recording_block_close');
  1520. var recording_block = document.getElementById('recording_block');
  1521. var PageLM = "2024-05-07 18:33";
  1522. var recording_button = document.getElementById('recording_button');
  1523. var stopButton = document.getElementById('stop');
  1524. var audio = document.getElementById('audio');
  1525. var recorder, audioBlob;
  1526. closeRecord.addEventListener('click', () => {
  1527. recPause();
  1528. console.log('record-click')
  1529. recording_block.classList.remove('show');
  1530. recording_block.classList.add('hidden');
  1531. });
  1532. function reclog(s, color) {
  1533. var now = new Date();
  1534. var t = ("0" + now.getHours()).substr(-2)
  1535. + ":" + ("0" + now.getMinutes()).substr(-2)
  1536. + ":" + ("0" + now.getSeconds()).substr(-2);
  1537. var div = document.createElement("div");
  1538. var elem = document.querySelector(".reclog");
  1539. elem.insertBefore(div, elem.firstChild);
  1540. div.innerHTML = '<div style="color:' + (!color ? "" : color == 1 ? "red" : color == 2 ? "#0b1" : color) + '">[' + t + ']' + s + '</div>';
  1541. };
  1542. window.onerror = function (message, url, lineNo, columnNo, error) {
  1543. //https://www.cnblogs.com/xianyulaodi/p/6201829.html
  1544. reclog('<span style="color:red">【Uncaught Error】' + message + '<pre>' + "at:" + lineNo + ":" + columnNo + " url:" + url + "\n" + (error && error.stack || Html_$T("kBaF::不能获得错误堆栈")) + '</pre></span>');
  1545. };
  1546. if (!window.Html_$T) {//没有提供本页面用的国际化多语言支持时 返回中文文本
  1547. window.Html_$T = function () {
  1548. var a = arguments, txt = a[0].replace(/^.+?::/, ""), n = 0;
  1549. for (var i = 0; i < a.length; i++) { if (typeof a[i] == "number") { n = i; break } }
  1550. txt = txt.replace(/\{(\d+)\}/g, function (v, f) { v = a[+f + n]; return v == null ? "" : v });
  1551. return txt;
  1552. }
  1553. window.Html_xT = function (v) { return v }
  1554. }
  1555. if (window.Recorder) {
  1556. // reclog(Html_$T('BL9u::頁面已準備好,請先點擊打開錄音,然後點擊錄製'), 2);
  1557. console.log('頁面已準備好,請先點擊打開錄音,然後點擊錄製')
  1558. } else {
  1559. reclog(Html_$T("YzPd::js文件加载失败,请刷新重试!"), "#f00;font-size:50px");
  1560. console.log('js文件加载失敗,请刷新重试!')
  1561. }
  1562. recording_button.addEventListener('click', async () => {
  1563. recording_block.classList.toggle('show');
  1564. recording_block.classList.toggle('hidden');
  1565. recStart();
  1566. });
  1567. function recStart() {//打开了录音后才能进行start、stop调用
  1568. rec.start();
  1569. };
  1570. stopButton.addEventListener('click', async () => {
  1571. // recorder.stop();
  1572. // uploadAudio(audioBlob);
  1573. recStop();
  1574. });
  1575. window.onload = function () {
  1576. recOpen();
  1577. };
  1578. // 錄音程式
  1579. // =======================
  1580. var rec, wave, recBlob;
  1581. /**调用open打开录音请求好录音权限 Call open to open the recording and request the recording permission**/
  1582. var recOpen = function () {//一般在显示出录音按钮或相关的录音界面时进行此方法调用,后面用户点击开始录音时就能畅通无阻了
  1583. rec = null;
  1584. wave = null;
  1585. recBlob = null;
  1586. var newRec = Recorder({
  1587. type: "mp3", sampleRate: 16000, bitRate: 16 //mp3格式,指定采样率hz、比特率kbps,其他参数使用默认配置;注意:是数字的参数必须提供数字,不要用字符串;需要使用的type类型,需提前把格式支持文件加载进来,比如使用wav格式需要提前加载wav.js编码引擎
  1588. , onProcess: function (buffers, powerLevel, bufferDuration, bufferSampleRate, newBufferIdx, asyncEnd) {
  1589. // // //录音实时回调,大约1秒调用12次本回调
  1590. document.querySelector(".recpowerx").style.width = powerLevel + "%";
  1591. document.querySelector(".recpowert").innerText = formatMs(bufferDuration, 1) + " / " + powerLevel;
  1592. // //可视化图形绘制
  1593. // wave.input(buffers[buffers.length - 1], powerLevel, bufferSampleRate);
  1594. }
  1595. });
  1596. newRec.open(function () {//打开麦克风授权获得相关资源
  1597. rec = newRec;
  1598. //此处创建这些音频可视化图形绘制浏览器支持妥妥的
  1599. // wave = Recorder.FrequencyHistogramView({ elem: ".recwave" });
  1600. reclog(Html_$T("GVCa::已打開錄音,可以點擊錄制開始錄音"), 2);
  1601. }, function (msg, isUserNotAllow) {//用户拒绝未授权或不支持
  1602. reclog((isUserNotAllow ? "UserNotAllow, " : "") + Html_$T("TOOV::打開錄音失敗:") + msg, 1);
  1603. });
  1604. };
  1605. /**关闭录音,释放资源 Close recording, release resources**/
  1606. function recClose() {
  1607. if (rec) {
  1608. rec.close();
  1609. reclog(Html_$T("jqOs::已关闭"));
  1610. } else {
  1611. reclog(Html_$T("VOOw::未打开录音"), 1);
  1612. };
  1613. };
  1614. /**开始录音 Start recording**/
  1615. function recStart() {//打开了录音后才能进行start、stop调用
  1616. if (rec && Recorder.IsOpen()) {
  1617. recBlob = null;
  1618. rec.start();
  1619. reclog(Html_$T("CGdy::已經開始錄音...") + " " + rec.set.type + " " + rec.set.sampleRate + " " + rec.set.bitRate + "kbps");
  1620. } else {
  1621. reclog(Html_$T("ajKR::未打开錄音"), 1);
  1622. };
  1623. };
  1624. /**暂停录音 Passing recording**/
  1625. function recPause() {
  1626. if (rec && Recorder.IsOpen()) {
  1627. rec.pause();
  1628. reclog(Html_$T("GvCy::已暂停"));
  1629. } else {
  1630. reclog(Html_$T("gCAR::未打開錄音"), 1);
  1631. };
  1632. };
  1633. /**恢复录音 Resume recording**/
  1634. function recResume() {
  1635. if (rec && Recorder.IsOpen()) {
  1636. rec.resume();
  1637. reclog(Html_$T("5q1K::继续录音中..."));
  1638. } else {
  1639. reclog(Html_$T("Ob6S::未打开录音"), 1);
  1640. };
  1641. };
  1642. /**结束录音,得到音频文件 Stop recording and get audio files**/
  1643. function recStop() {
  1644. if (!(rec && Recorder.IsOpen())) {
  1645. reclog(Html_$T("5JuL::未打開錄音"), 1);
  1646. return;
  1647. };
  1648. rec.stop(function (blob, duration) {
  1649. console.log(blob, (window.URL || webkitURL).createObjectURL(blob), Html_xT(Html_$T("gOix::時長:{1}ms", 0, duration)));
  1650. recBlob = blob;
  1651. var file = new File([blob], "recording.mp3", { type: "audio/mp3" });
  1652. console.log(file);
  1653. handleAudioToText(file);
  1654. reclog(Html_$T("0LHf::已錄製mp3:{1}ms {2}字節,可以點擊播放、上傳、本地下载了", 0, formatMs(duration), blob.size), 2);
  1655. }, function (msg) {
  1656. reclog(Html_$T("kGZO::錄音失敗:") + msg, 1);
  1657. });
  1658. };
  1659. /**播放 Play**/
  1660. function recPlay() {
  1661. if (!recBlob) {
  1662. reclog(Html_$T("tIke::请先錄音,然后停止後再播放"), 1);
  1663. return;
  1664. };
  1665. var cls = ("a" + Math.random()).replace(".", "");
  1666. reclog(Html_$T('GlWb::播放中: ') + '<span class="' + cls + '"></span>');
  1667. var audio = document.createElement("audio");
  1668. audio.controls = true;
  1669. document.querySelector("." + cls).appendChild(audio);
  1670. //简单利用URL生成播放地址,注意不用了时需要revokeObjectURL,否则霸占内存
  1671. audio.src = (window.URL || webkitURL).createObjectURL(recBlob);
  1672. audio.play();
  1673. setTimeout(function () {
  1674. (window.URL || webkitURL).revokeObjectURL(audio.src);
  1675. }, 5000);
  1676. };
  1677. /**上传 Upload**/
  1678. function recUpload() {
  1679. var blob = recBlob;
  1680. if (!blob) {
  1681. reclog(Html_$T("DUTn::请先录音,然后停止后再上传"), 1);
  1682. return;
  1683. };
  1684. //本例子假设使用原始XMLHttpRequest请求方式,实际使用中自行调整为自己的请求方式
  1685. //录音结束时拿到了blob文件对象,可以用FileReader读取出内容,或者用FormData上传
  1686. var api = "http://127.0.0.1:9528";
  1687. var onreadystatechange = function (xhr, title) {
  1688. return function () {
  1689. if (xhr.readyState == 4) {
  1690. if (xhr.status == 200) {
  1691. reclog(title + Html_$T("G2MU::上传成功") + ' <span style="color:#999">response: ' + xhr.responseText + '</span>', 2);
  1692. } else {
  1693. reclog(title + Html_$T("TUdi::没有完成上传,演示上传地址无需关注上传结果,只要浏览器控制台内Network面板内看到的请求数据结构是预期的就ok了。"), "#d8c1a0");
  1694. console.error(Html_xT(title + Html_$T("HjDi::上传失败")), xhr.status, xhr.responseText);
  1695. };
  1696. };
  1697. };
  1698. };
  1699. reclog(Html_$T("QnSI::开始上传到{1},请稍候... (你可以先到源码 /assets/node-localServer 目录内执行 npm run start 来运行本地测试服务器)", 0, api));
  1700. /***方式一:将blob文件转成base64纯文本编码,使用普通application/x-www-form-urlencoded表单上传***/
  1701. var reader = new FileReader();
  1702. reader.onloadend = function () {
  1703. var postData = "";
  1704. postData += "mime=" + encodeURIComponent(blob.type);//告诉后端,这个录音是什么格式的,可能前后端都固定的mp3可以不用写
  1705. postData += "&upfile_b64=" + encodeURIComponent((/.+;\s*base64\s*,\s*(.+)$/i.exec(reader.result) || [])[1]) //录音文件内容,后端进行base64解码成二进制
  1706. //...其他表单参数
  1707. var xhr = new XMLHttpRequest();
  1708. xhr.open("POST", api + "/uploadBase64");
  1709. xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  1710. xhr.onreadystatechange = onreadystatechange(xhr, Html_$T("gG1f::上传方式一【Base64】"));
  1711. xhr.send(postData);
  1712. };
  1713. reader.readAsDataURL(blob);
  1714. /***方式二:使用FormData用multipart/form-data表单上传文件***/
  1715. var form = new FormData();
  1716. form.append("upfile", blob, "recorder.mp3"); //和普通form表单并无二致,后端接收到upfile参数的文件,文件名为recorder.mp3
  1717. //...其他表单参数
  1718. var xhr = new XMLHttpRequest();
  1719. xhr.open("POST", api + "/upload");
  1720. xhr.onreadystatechange = onreadystatechange(xhr, Html_$T("vDzB::上传方式二【FormData】"));
  1721. xhr.send(form);
  1722. };
  1723. /**本地下载 Local download**/
  1724. function recLocalDown() {
  1725. if (!recBlob) {
  1726. reclog(Html_$T("M86h::请先录音,然后停止后再下载"), 1);
  1727. return;
  1728. };
  1729. var cls = ("a" + Math.random()).replace(".", "");
  1730. recdown64.lastCls = cls;
  1731. reclog(Html_$T('vJPl::点击 ') + '<span class="' + cls + '"></span>' + Html_$T('Whtc:: 下载,或复制文本')
  1732. + '<button onclick="recdown64(\'' + cls + '\')">' + Html_$T('XK4l::生成Base64文本') + '</button><span class="' + cls + '_b64"></span>');
  1733. var fileName = "recorder-" + Date.now() + ".mp3";
  1734. var downA = document.createElement("A");
  1735. downA.innerHTML = Html_$T("g8Fy::下载 ") + fileName;
  1736. downA.href = (window.URL || webkitURL).createObjectURL(recBlob);
  1737. downA.download = fileName;
  1738. document.querySelector("." + cls).appendChild(downA);
  1739. if (/mobile/i.test(navigator.userAgent)) {
  1740. alert(Html_xT(Html_$T("DIEK::因移动端绝大部分国产浏览器未适配Blob Url的下载,所以本demo代码在移动端未调用downA.click()。请尝试点击日志中显示的下载链接下载")));
  1741. } else {
  1742. downA.click();
  1743. }
  1744. //不用了时需要revokeObjectURL,否则霸占内存
  1745. //(window.URL||webkitURL).revokeObjectURL(downA.href);
  1746. };
  1747. function recdown64(cls) {
  1748. var el = document.querySelector("." + cls + "_b64");
  1749. if (recdown64.lastCls != cls) {
  1750. el.innerHTML = '<span style="color:red">' + Html_$T("eKKx::老的数据没有保存,只支持最新的一条") + '</span>';
  1751. return;
  1752. }
  1753. var reader = new FileReader();
  1754. reader.onloadend = function () {
  1755. el.innerHTML = '<textarea></textarea>';
  1756. el.querySelector("textarea").value = reader.result;
  1757. };
  1758. reader.readAsDataURL(recBlob);
  1759. };
  1760. var formatMs = function (ms, all) {
  1761. var ss = ms % 1000; ms = (ms - ss) / 1000;
  1762. var s = ms % 60; ms = (ms - s) / 60;
  1763. var m = ms % 60; ms = (ms - m) / 60;
  1764. var h = ms;
  1765. var t = (h ? h + ":" : "")
  1766. + (all || h + m ? ("0" + m).substr(-2) + ":" : "")
  1767. + (all || h + m + s ? ("0" + s).substr(-2) + "″" : "")
  1768. + ("00" + ss).substr(-3);
  1769. return t;
  1770. };
  1771. // =======================
  1772. let mediaRecorder;
  1773. let audioChunks = [];
  1774. async function handleAudioToText(file) {
  1775. console.log('tts')
  1776. let audioLang = "cmn-Hant-TW"; // 音訊語言
  1777. // let lang = localStorage.getItem("lang");
  1778. let lang = "zh-tw";
  1779. console.log("lang", lang);
  1780. switch (lang) {
  1781. case "zh-tw":
  1782. audioLang = "cmn-Hant-TW";
  1783. break;
  1784. case "en-us":
  1785. audioLang = "en-US";
  1786. break;
  1787. case "ja-jp":
  1788. audioLang = "ja-JP";
  1789. break;
  1790. case "ko-kr":
  1791. audioLang = "ko-KR";
  1792. break;
  1793. default:
  1794. break;
  1795. }
  1796. let url = `https://cmm.ai:9001/gcp/speech-to-text?language_code=${audioLang}`;
  1797. const formData = new FormData();
  1798. formData.append("file", file);
  1799. try {
  1800. const response = await axios.post(url, formData);
  1801. console.log("response", response);
  1802. input_text_value = response.data;
  1803. recording_block.classList.remove('show');
  1804. recording_block.classList.add('hidden');
  1805. if (input_text_value.length === 0) {
  1806. alert('請再說一次')
  1807. return
  1808. }
  1809. console.log(input_text_value[0]);
  1810. get_data(input_text_value);
  1811. } catch (error) {
  1812. console.log("error", error);
  1813. }
  1814. }