You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1980 lines
54 KiB

  1. <!-- @format -->
  2. <template>
  3. <!-- 容器 -->
  4. <view class="container">
  5. <!-- 标题 -->
  6. <view class="title-container">
  7. <view class="title">
  8. <image class="back-homepage-btn" src="/static/marketSituation-image/back.png" mode="返回按钮" @click="backToHomepage()"> </image>
  9. <view class="mid-title">
  10. <image class="left-page" src="/static/img/left-page.png" mode="向左翻页"></image>
  11. <view class="stock-id">
  12. <view class="stock-name"> {{ stockInformation.stockName }} </view>
  13. <view class="stock-code"> {{ stockInformation.stockCode }} </view>
  14. </view>
  15. <image class="right-page" src="/static/img/right-page.png" mode="向右翻页"></image>
  16. </view>
  17. <image class="search" src="/static/marketSituation-image/search.png" mode="搜索" @click="startTcp()"> </image>
  18. <view class="more" @click="disconnect()">···</view>
  19. </view>
  20. </view>
  21. <view class="body">
  22. <!-- 股票信息栏 -->
  23. <view class="stock-information" @click="openStockDetail()">
  24. <view v-if="isStockDetail" class="stock-detail-container" @click.stop @click="closeStockDetail()">
  25. <view class="stock-detail" @click.stop>
  26. <view class="first-column">
  27. <view class="first-column-data" v-for="item in firstColumData" :key="item">
  28. <view class="stock-detail-title">
  29. {{ item.title }}
  30. </view>
  31. <view class="stock-detail-value">
  32. {{ item.value }}
  33. </view>
  34. </view>
  35. </view>
  36. <view class="second-column">
  37. <view class="second-column-data" v-for="item in secondColumnData" :key="item">
  38. <view class="stock-detail-title">
  39. {{ item.title }}
  40. </view>
  41. <view class="stock-detail-value">
  42. {{ item.value }}
  43. </view>
  44. </view>
  45. </view>
  46. </view>
  47. </view>
  48. <view class="stock-current-data">
  49. <view class="stock-current-price" :class="confirmStockColor(stockInformation.currentPrice, stockInformation.lastDayStockClosePrice)">
  50. {{ Number(stockInformation.currentPrice).toFixed(2) }}
  51. </view>
  52. <view class="stock-current-other">
  53. <view class="stock-current-value" :class="confirmStockColor(stockInformation.currentValue)">
  54. {{ Number(stockInformation.currentValue).toFixed(2) }}
  55. </view>
  56. <view class="stock-current-ratio" :class="confirmStockColor(stockInformation.currentRatio)"> {{ Number(stockInformation.currentRatio).toFixed(2) }}% </view>
  57. </view>
  58. </view>
  59. <view class="stock-other-data">
  60. <view class="first-line">
  61. <view class="high-price">
  62. <view class="value" :class="confirmStockColor(stockInformation.highPrice, stockInformation.lastDayStockClosePrice)">
  63. {{ Number(stockInformation.highPrice).toFixed(2) }}
  64. </view>
  65. </view>
  66. <view class="volume">
  67. <view class="value">
  68. {{ utils.formatStockNumber(stockInformation.volume, 2) }}
  69. </view>
  70. </view>
  71. <view class="volume-ratio">
  72. 量比
  73. <view class="value">
  74. {{ Number(stockInformation.volumeRatio).toFixed(2) }}
  75. </view>
  76. </view>
  77. </view>
  78. <view class="second-line">
  79. <view class="low-price">
  80. <view class="value" :class="confirmStockColor(stockInformation.lowPrice, stockInformation.lastDayStockClosePrice)">
  81. {{ Number(stockInformation.lowPrice).toFixed(2) }}
  82. </view>
  83. </view>
  84. <view class="amount">
  85. <view class="value">
  86. {{ utils.formatStockNumber(stockInformation.amount, 2) }}
  87. </view>
  88. </view>
  89. <view class="market-earn">
  90. 市盈
  91. <view class="value">
  92. {{ Number(stockInformation.marketEarn).toFixed(2) }}
  93. </view>
  94. </view>
  95. </view>
  96. <view class="third-line">
  97. <view class="open-price">
  98. <view class="value" :class="confirmStockColor(stockInformation.openPrice, stockInformation.lastDayStockClosePrice)">
  99. {{ Number(stockInformation.openPrice).toFixed(2) }}
  100. </view>
  101. </view>
  102. <view class="turnover-ratio">
  103. <view class="value"> {{ Number(stockInformation.turnoverRatio).toFixed(2) }}% </view>
  104. </view>
  105. <view class="market-value">
  106. 市值
  107. <view class="value">
  108. {{ utils.formatStockNumber(stockInformation.marketValue, 2) }}
  109. </view>
  110. </view>
  111. </view>
  112. </view>
  113. </view>
  114. <!-- 股票图表 -->
  115. <view class="stock-chart">
  116. <view class="stock-kline-tab">
  117. <!-- 1:分时 2:日K 3:周K 4:月K -->
  118. <view class="tab-time" :class="{ 'tab-selected': klineTab == 1 }" @click="selectKlineTab(1)"> 分时 </view>
  119. <view class="tab-day" :class="{ 'tab-selected': klineTab == 2 }" @click="selectKlineTab(2)"> 日K </view>
  120. <view class="tab-week" :class="{ 'tab-selected': klineTab == 3 }" @click="selectKlineTab(3)"> 周K </view>
  121. <view class="tab-month" :class="{ 'tab-selected': klineTab == 4 }" @click="selectKlineTab(4)"> 月K </view>
  122. <view class="tab-more" :class="{ 'tab-selected': klineTab != 1 && klineTab != 2 && klineTab != 3 && klineTab != 4 }" @click="isMoreTabs ? closeMoreTabs() : openMoreTabs()">
  123. <view class="more-no-choose" v-if="klineTab == 1 || klineTab == 2 || klineTab == 3 || klineTab == 4"> 更多 </view>
  124. <view class="more-choose" v-else>
  125. {{ chooseTabName(klineTab) }}
  126. </view>
  127. <view :class="[isMoreTabs ? 'arrow-down' : 'arrow-up']"> </view>
  128. </view>
  129. <view class="tab-setting">
  130. <image class="tab-setting-img" src="/static/marketSituation-image/marketCondition-image/setting2.png" mode="设置"></image>
  131. </view>
  132. </view>
  133. <view v-if="isMoreTabs" class="moreTabsContainer">
  134. <view v-for="item in moreTabsData" :key="item" class="moreTabItem" :class="{ 'tab-selected': klineTab == item.value }" @click="selectMoreTab(item.value)">
  135. {{ item.title }}
  136. </view>
  137. </view>
  138. <view class="stock-kline">
  139. <view v-if="klineTab === 1 || klineTab === 2" class="time-chart-container" style="position: relative">
  140. <!-- 主图Canvas -->
  141. <canvas
  142. canvas-id="stockChart"
  143. class="stock-chart"
  144. :width="canvasWidth"
  145. :height="canvasHeight"
  146. :style="{
  147. width: canvasWidth + 'px',
  148. height: canvasHeight + 'px',
  149. pointerEvents: 'none',
  150. }"
  151. will-read-frequently="true"
  152. ></canvas>
  153. <!-- 动态数据Canvas层 -->
  154. <canvas
  155. canvas-id="dynamicCanvas"
  156. id="dynamicCanvas"
  157. :width="canvasWidth"
  158. :height="canvasHeight"
  159. :style="{
  160. width: canvasWidth + 'px',
  161. height: canvasHeight + 'px',
  162. pointerEvents: 'none',
  163. position: 'absolute',
  164. top: '0',
  165. left: '0',
  166. }"
  167. will-read-frequently="true"
  168. ></canvas>
  169. <!-- 十字准心Canvas层 -->
  170. <canvas
  171. canvas-id="crosshairCanvas"
  172. id="crosshairCanvas"
  173. :width="canvasWidth"
  174. :height="canvasHeight"
  175. :style="{
  176. width: canvasWidth + 'px',
  177. height: canvasHeight + 'px',
  178. position: 'absolute',
  179. top: '0',
  180. left: '0',
  181. }"
  182. will-read-frequently="true"
  183. @touchstart="touchStart"
  184. @touchmove="touchMove"
  185. @touchend="touchEnd"
  186. ></canvas>
  187. </view>
  188. <!-- K线图区域 -->
  189. <view class="test" v-else-if="klineTab === 3">
  190. <button @click="sendGetTimeData()">接收消息</button>
  191. <button @click="sendStopTimeData()">停止消息</button>
  192. </view>
  193. <view v-else class="kline-chart-container">
  194. <text>K线图开发中...</text>
  195. </view>
  196. </view>
  197. </view>
  198. </view>
  199. <view class="bottomTool">
  200. <view class="index">
  201. <image class="icon" src="/static/marketSituation-image/marketCondition-image/index.png" mode="指标仓库图标"> </image>
  202. 指标仓库
  203. </view>
  204. <view class="function">
  205. <image class="icon" src="/static/marketSituation-image/marketCondition-image/function.png" mode="功能图标"> </image>
  206. 功能
  207. </view>
  208. <view class="favorites">
  209. <image class="icon" src="/static/marketSituation-image/marketCondition-image/favorites.png" mode="加自选图标"></image>
  210. 加自选
  211. </view>
  212. </view>
  213. </view>
  214. </template>
  215. <script setup>
  216. import { ref, reactive, computed, onMounted, watch, nextTick, onUnmounted, getCurrentInstance } from "vue";
  217. const instance = getCurrentInstance();
  218. import { prevClosePrice, timeData as testTimeData, klineData as testKlineData } from "@/common/stockTimeInformation.js";
  219. import { throttle } from "@/common/util.js";
  220. import { HCharts } from "@/common/canvasMethod.js";
  221. // const TCPSocket = uni.requireNativePlugin("Aimer-TCPPlugin");
  222. const tcpObject = {
  223. ip: "192.168.1.9",
  224. port: 8080,
  225. reconnectInterval: 3000,
  226. isConnected: false,
  227. };
  228. const TIME_OUT = 1000 * 5;
  229. const resultR = ref([]);
  230. // 股票信息栏变量
  231. const stockInformation = ref({
  232. stockName: "----", //股票名称
  233. stockCode: "------", //股票代码
  234. lastDayStockClosePrice: 0.0, //前一日收盘价
  235. currentPrice: 0.0, //当前股价
  236. currentValue: 0.0, //涨跌额度
  237. currentRatio: 0.0, //涨跌幅度
  238. highPrice: 0.0, //最高价
  239. lowPrice: 0.0, //最低价
  240. openPrice: 0.0, //开盘价
  241. closePrice: 0.0, //收盘价
  242. volume: 0.0, //成交量
  243. volumeRatio: 0.0, //成交量比
  244. amount: 0.0, //成交额
  245. marketEarn: 0.0, //市盈
  246. turnoverRatio: 0.0, //换手率
  247. marketValue: 0.0, //市值
  248. });
  249. // 是否展开股票信息细节栏的判断变量
  250. const isStockDetail = ref(false);
  251. // 股票信息细节内容变量
  252. const firstColumData = [
  253. {
  254. title: "振幅",
  255. value: 0,
  256. },
  257. {
  258. title: "现手",
  259. value: 0,
  260. },
  261. {
  262. title: "内盘",
  263. value: 0,
  264. },
  265. {
  266. title: "外盘",
  267. value: 0,
  268. },
  269. {
  270. title: "流通股",
  271. value: 0,
  272. },
  273. {
  274. title: "每股净资产",
  275. value: 0,
  276. },
  277. {
  278. title: "净资产收益率",
  279. value: 0,
  280. },
  281. {
  282. title: "总股本",
  283. value: 0,
  284. },
  285. {
  286. title: "总资本",
  287. value: 0,
  288. },
  289. {
  290. title: "总市值",
  291. value: 0,
  292. },
  293. {
  294. title: "一个月最高",
  295. value: 0,
  296. },
  297. {
  298. title: "一个月最低",
  299. value: 0,
  300. },
  301. ];
  302. const secondColumnData = [
  303. {
  304. title: "均价",
  305. value: 0,
  306. },
  307. {
  308. title: "昨收",
  309. value: 0,
  310. },
  311. {
  312. title: "委比",
  313. value: 0,
  314. },
  315. {
  316. title: "委买",
  317. value: 0,
  318. },
  319. {
  320. title: "委卖",
  321. value: 0,
  322. },
  323. {
  324. title: "市盈利(静)",
  325. value: 0,
  326. },
  327. {
  328. title: "市盈利(动)",
  329. value: 0,
  330. },
  331. {
  332. title: "市净率",
  333. value: 0,
  334. },
  335. {
  336. title: "涨停价",
  337. value: 0,
  338. },
  339. {
  340. title: "跌停价",
  341. value: 0,
  342. },
  343. {
  344. title: "一年最高",
  345. value: 0,
  346. },
  347. {
  348. title: "一年最低",
  349. value: 0,
  350. },
  351. ];
  352. // 是否展开更多Tab的判断变量
  353. const isMoreTabs = ref(false);
  354. const moreTabsData = ref([
  355. {
  356. title: "1分",
  357. value: 5,
  358. },
  359. {
  360. title: "5分",
  361. value: 6,
  362. },
  363. {
  364. title: "15分",
  365. value: 7,
  366. },
  367. {
  368. title: "30分",
  369. value: 8,
  370. },
  371. {
  372. title: "60分",
  373. value: 9,
  374. },
  375. {
  376. title: "季K",
  377. value: 10,
  378. },
  379. {
  380. title: "年K",
  381. value: 11,
  382. },
  383. ]);
  384. // 股票当前选中的K线类型Tab
  385. // 1:分时 2:日K 3:周K 4:月K
  386. const klineTab = ref(2);
  387. const sendGetTimeData = () => {
  388. console.log("执行发送消息的方法");
  389. try {
  390. TCPSocket.send({
  391. channel: "1",
  392. message: '{"command": "real_time", "stock_code": "SH.000001"}',
  393. });
  394. } catch (e) {
  395. console.log("error", e);
  396. }
  397. };
  398. const sendStopTimeData = () => {
  399. try {
  400. TCPSocket.send({
  401. channel: "1",
  402. message: '{"command": "stop_real_time"}',
  403. });
  404. } catch (e) {
  405. console.log("error", e);
  406. }
  407. };
  408. // 确定股票数据的颜色方法
  409. const confirmStockColor = (price, lastDayStockClosePrice) => {
  410. if (typeof lastDayStockClosePrice === "undefined") {
  411. if (price == 0) {
  412. return "price-none";
  413. } else if (price > 0) {
  414. return "price-up";
  415. } else {
  416. return "price-down";
  417. }
  418. } else {
  419. if (price == lastDayStockClosePrice) {
  420. return "price-none";
  421. } else if (price > lastDayStockClosePrice) {
  422. return "price-up";
  423. } else {
  424. return "price-down";
  425. }
  426. }
  427. };
  428. // 股票K线类型方法
  429. const selectKlineTab = (tabId) => {
  430. klineTab.value = tabId;
  431. if (tabId === 1) {
  432. stockInformation.value.lastDayStockClosePrice = prevClosePrice;
  433. }
  434. initCanvas();
  435. // startAddDataTimer();
  436. };
  437. // 返回按钮
  438. const backToHomepage = () => {
  439. const pages = getCurrentPages();
  440. if (pages.length > 1) {
  441. uni.navigateBack();
  442. } else {
  443. // 如果没有上一页,跳转到首页
  444. uni.reLaunch({
  445. url: "/pages/home/home",
  446. });
  447. }
  448. };
  449. const openStockDetail = () => {
  450. isStockDetail.value = true;
  451. };
  452. const closeStockDetail = () => {
  453. isStockDetail.value = false;
  454. };
  455. const openMoreTabs = () => {
  456. isMoreTabs.value = true;
  457. };
  458. const closeMoreTabs = () => {
  459. isMoreTabs.value = false;
  460. };
  461. const selectMoreTab = (value) => {
  462. selectKlineTab(value);
  463. };
  464. const chooseTabName = () => {
  465. if (klineTab.value === 5) {
  466. return "1分";
  467. } else if (klineTab.value === 6) {
  468. return "5分";
  469. } else if (klineTab.value === 7) {
  470. return "15分";
  471. } else if (klineTab.value === 8) {
  472. return "30分";
  473. } else if (klineTab.value === 9) {
  474. return "60分";
  475. } else if (klineTab.value === 10) {
  476. return "季K";
  477. } else if (klineTab.value === 11) {
  478. return "年K";
  479. }
  480. };
  481. // 画布对象
  482. const canvasWidth = ref(100);
  483. const canvasHeight = ref(100);
  484. const CANVAS_BACKGROUND_COLOR = "#fff";
  485. const TEXT_COLOR1 = "#000";
  486. const TEXT_COLOR2 = "red";
  487. const LINE_COLOR = "#e5e5e5";
  488. const timeChartObject = ref({
  489. min: 0,
  490. max: 0,
  491. });
  492. const klineChartObject = ref({
  493. min: 0,
  494. max: 0,
  495. });
  496. const chartRange = ref();
  497. // 开盘时间
  498. const openTime = "09:30";
  499. // 收盘时间
  500. const closeTime = "15:00";
  501. const ctx = ref(null);
  502. const dynamicCtx = ref(null); // 动态Canvas上下文
  503. const crosshairCtx = ref(null); // 十字准心Canvas上下文
  504. const pixelRatio = ref(1);
  505. // 触屏对象
  506. const touchState = reactive({
  507. startX: 0,
  508. startY: 0,
  509. isMoving: false,
  510. moveDistance: 0,
  511. moveThreshold: 10, //移动阈值(用于判断是否在点击)
  512. scale: 1, // 当前缩放比例
  513. minScale: 0.3, // 最小缩放比例
  514. maxScale: 5, // 最大缩放比例
  515. baseVisibleCount: 40, // 基准可见K线数量
  516. offset: 0, // 数据偏移量
  517. isZooming: false, // 是否正在缩放
  518. initialDistance: 0, // 初始两指距离
  519. initialScale: 1, // 初始缩放比例
  520. });
  521. // 计算当前可见的K线数量
  522. const visibleCount = computed(() => {
  523. return Math.floor(touchState.baseVisibleCount / touchState.scale);
  524. });
  525. // 计算当前显示的数据范围
  526. const visibleDataRange = computed(() => {
  527. const start = Math.max(0, klineData.value.length - visibleCount.value - touchState.offset);
  528. const end = Math.min(klineData.value.length, start + visibleCount.value);
  529. return {
  530. start,
  531. end,
  532. };
  533. });
  534. // 获取当前可见的数据
  535. const visibleKlineData = computed(() => {
  536. const { start, end } = visibleDataRange.value;
  537. return klineData.value.slice(start, end);
  538. });
  539. // 计算两点之间的距离
  540. const getDistance = (touch1, touch2) => {
  541. const dx = touch1.x - touch2.x;
  542. const dy = touch1.y - touch2.y;
  543. return Math.sqrt(dx * dx + dy * dy);
  544. };
  545. // 十字准线相关状态
  546. const crosshair = reactive({
  547. show: false,
  548. x: 0,
  549. y: 0,
  550. currentData: null,
  551. snapToData: true,
  552. });
  553. // 绘制网格和坐标轴
  554. const grid = [
  555. {
  556. top: 20,
  557. bottom: canvasHeight.value * 0.5,
  558. left: 5,
  559. right: 5,
  560. lineColor: LINE_COLOR,
  561. lineWidth: 1,
  562. horizontalLineNum: 5,
  563. verticalLineNum: 5,
  564. },
  565. {
  566. top: canvasHeight.value * 0.5 + 20,
  567. bottom: 20,
  568. left: 5,
  569. right: 5,
  570. lineColor: LINE_COLOR,
  571. lineWidth: 1,
  572. horizontalLineNum: 3,
  573. verticalLineNum: 5,
  574. },
  575. ];
  576. // 绘制网格和坐标轴
  577. const dayGrid = [
  578. {
  579. top: 20,
  580. bottom: canvasHeight.value * 0.5,
  581. left: 5,
  582. right: 5,
  583. lineColor: LINE_COLOR,
  584. lineWidth: 1,
  585. horizontalLineNum: 5,
  586. verticalLineNum: 2,
  587. },
  588. {
  589. top: canvasHeight.value * 0.5 + 20,
  590. bottom: 20,
  591. left: 5,
  592. right: 5,
  593. lineColor: LINE_COLOR,
  594. lineWidth: 1,
  595. horizontalLineNum: 3,
  596. verticalLineNum: 2,
  597. },
  598. {
  599. top: canvasHeight.value * 0.5 + 20,
  600. bottom: 20,
  601. left: 5,
  602. right: 5,
  603. lineColor: LINE_COLOR,
  604. lineWidth: 1,
  605. horizontalLineNum: 3,
  606. verticalLineNum: 2,
  607. },
  608. ];
  609. // 工具函数
  610. const utils = {
  611. // 格式化价格
  612. formatPrice(price) {
  613. return price.toFixed(2);
  614. },
  615. // 计算数据范围
  616. calculateDataRange(data, key) {
  617. if (!data || data.length === 0) {
  618. return {
  619. min: 0,
  620. max: 0,
  621. };
  622. }
  623. const values = data.map((item) => item[key]);
  624. return {
  625. min: Math.min(...values),
  626. max: Math.max(...values),
  627. };
  628. },
  629. // 计算标签
  630. calculateLabel(data, type = 2, preClosePrice = 0, key, num) {
  631. let label = [];
  632. if (key === "price") {
  633. // 分时价格区间
  634. if (type == 1) {
  635. const priceRange = utils.calculateDataRange(data, "price");
  636. const theMost = Math.max(priceRange.max - preClosePrice, preClosePrice - priceRange.min);
  637. const mid = (num - 1) / 2;
  638. // 计算分时价格标签
  639. label[mid] = {
  640. value: utils.formatPrice(preClosePrice),
  641. ratio: utils.formatPrice(0) + "%",
  642. };
  643. for (let i = 0; i < mid; i++) {
  644. label[i] = {
  645. value: utils.formatPrice(preClosePrice + (theMost * (mid - i)) / mid),
  646. ratio: utils.formatPrice((100 * (theMost * (mid - i))) / mid / preClosePrice) + "%",
  647. };
  648. label[num - 1 - i] = {
  649. value: utils.formatPrice(preClosePrice - (theMost * (mid - i)) / mid),
  650. ratio: utils.formatPrice((-1 * 100 * (theMost * (mid - i))) / mid / preClosePrice) + "%",
  651. };
  652. }
  653. chartRange.value.push({
  654. max: preClosePrice + theMost,
  655. min: preClosePrice - theMost,
  656. });
  657. // timeChartObject.value.max = preClosePrice + theMost;
  658. // timeChartObject.value.min = preClosePrice - theMost;
  659. return label;
  660. } else {
  661. const highPriceRange = utils.calculateDataRange(data, "high");
  662. const lowPriceRange = utils.calculateDataRange(data, "low");
  663. const priceRange = {
  664. max: highPriceRange.max * 1.01,
  665. min: lowPriceRange.min * 0.99,
  666. };
  667. const priceDiff = priceRange.max - priceRange.min;
  668. for (let i = 0; i < num; ++i) {
  669. label[i] = {
  670. value: utils.formatPrice(priceRange.max - (i * priceDiff) / (num - 1)),
  671. };
  672. }
  673. chartRange.value.push(priceRange);
  674. // klineChartObject.value.max = highPriceRange.max * 1.01;
  675. // klineChartObject.value.min = lowPriceRange.min * 0.99;
  676. return label;
  677. }
  678. } else if (key === "volume") {
  679. const volumeRange = utils.calculateDataRange(data, "volume");
  680. chartRange.value.push({
  681. max: volumeRange.max,
  682. min: 0,
  683. });
  684. label[0] = {
  685. value: utils.formatPrice(volumeRange.max),
  686. };
  687. label[1] = {
  688. value: utils.formatPrice(0),
  689. };
  690. return label;
  691. }
  692. return null;
  693. },
  694. // 线性插值
  695. lerp(start, end, factor) {
  696. return start + (end - start) * factor;
  697. },
  698. // 根据X坐标找到最近的数据点
  699. findNearestDataPoint(x, pointLen, data, grid, offset) {
  700. if (!data.length) return null;
  701. const width = canvasWidth.value;
  702. const height = canvasHeight.value;
  703. // 计算每个数据点的X坐标间隔
  704. // 倒推 const x=5+(index*(width-10)/pointLen) 已知x求index
  705. const xStep = width - grid[0].left - grid[0].right;
  706. // 计算触摸点对应的数据索引
  707. const touchX = (x - grid[0].left - offset) * pointLen;
  708. let nearestIndex = Math.round(touchX / xStep);
  709. let dataX;
  710. // 确保索引在有效范围内
  711. if (nearestIndex >= 0 && nearestIndex <= data.length - 1) {
  712. dataX = offset + grid[0].left + (nearestIndex * (width - grid[0].left - grid[0].right)) / pointLen;
  713. } else {
  714. dataX = x;
  715. }
  716. nearestIndex = Math.max(0, Math.min(nearestIndex, data.length - 1));
  717. return {
  718. ...data[nearestIndex],
  719. index: nearestIndex,
  720. x: dataX,
  721. };
  722. },
  723. // 根据Y坐标计算价格
  724. calculatePriceFromY(y, data, grid) {
  725. if (!data.length) return 0;
  726. const width = canvasWidth.value;
  727. const height = canvasHeight.value;
  728. // 上下边距1
  729. const topPadding1 = 20;
  730. const bottomPadding1 = height * 0.4;
  731. // 上下边距2
  732. const topPadding2 = height - bottomPadding1 + 40;
  733. const bottomPadding2 = 5;
  734. // 左右边距
  735. const verticalPadding = 5;
  736. let chartY;
  737. let price;
  738. for (let i = 0; i < grid.length; i++) {
  739. if (y >= grid[i].top && y <= height - grid[i].bottom) {
  740. const chartDiff = chartRange.value[i].max - chartRange.value[i].min;
  741. chartY = y - grid[i].top;
  742. price = chartRange.value[i].max - (chartY / (height - grid[i].bottom - grid[i].top)) * chartDiff;
  743. break;
  744. }
  745. }
  746. // if (y >= topPadding1 && y <= height - bottomPadding1) {
  747. // const priceDiff = priceRange.max - priceRange.min;
  748. // chartY = y - topPadding1;
  749. // price = priceRange.max - (chartY / (height - topPadding1 - bottomPadding1)) * priceDiff;
  750. // } else if (y >= topPadding2 && y <= height - bottomPadding2) {
  751. // const volumeRange = utils.calculateDataRange(data, "volume");
  752. // const volumeDiff = volumeRange.max - 0;
  753. // chartY = y - topPadding2;
  754. // price = volumeRange.max - (chartY / (height - topPadding2 - bottomPadding2)) * volumeDiff;
  755. // }
  756. return price;
  757. },
  758. // 股市数值格式化方法
  759. formatStockNumber(value, decimalPlaces = 2) {
  760. const num = Number(value);
  761. if (isNaN(num)) return "0";
  762. const absNum = Math.abs(num);
  763. const sign = num < 0 ? "-" : "";
  764. if (absNum >= 1000000000000) {
  765. // 万亿级别
  766. return sign + (absNum / 1000000000000).toFixed(decimalPlaces) + "万亿";
  767. } else if (absNum >= 100000000) {
  768. // 亿级别
  769. return sign + (absNum / 100000000).toFixed(decimalPlaces) + "亿";
  770. } else if (absNum >= 10000) {
  771. // 万级别
  772. return sign + (absNum / 10000).toFixed(decimalPlaces) + "万";
  773. } else {
  774. // 小于万的直接显示
  775. return sign + absNum.toFixed(decimalPlaces);
  776. }
  777. },
  778. };
  779. let text = [
  780. [
  781. {
  782. name: "领先",
  783. value: "暂无数据",
  784. color: "red",
  785. },
  786. {
  787. name: "价",
  788. value: utils.formatPrice(stockInformation.value.currentPrice),
  789. color: "black",
  790. },
  791. ],
  792. [
  793. {
  794. name: "量",
  795. value: utils.formatStockNumber(stockInformation.value.volume),
  796. color: "green",
  797. },
  798. {
  799. name: "额",
  800. value: "暂无数据",
  801. color: "black",
  802. },
  803. ],
  804. ];
  805. // 示例数据
  806. const timeData = ref([]);
  807. const klineData = ref([]);
  808. const initCanvas = async () => {
  809. try {
  810. crosshair.show = false;
  811. grid[0].bottom = canvasHeight.value * 0.4;
  812. grid[1].top = canvasHeight.value * 0.6 + 30;
  813. dayGrid[0].top = 20;
  814. dayGrid[0].bottom = canvasHeight.value * 0.6;
  815. dayGrid[1].top = canvasHeight.value * 0.4 + 30;
  816. dayGrid[1].bottom = canvasHeight.value * 0.3;
  817. dayGrid[2].top = canvasHeight.value * 0.7 + 20;
  818. dayGrid[2].bottom = 20;
  819. // 等待DOM更新
  820. await nextTick();
  821. ctx.value = uni.createCanvasContext("stockChart", instance.proxy);
  822. // 初始化动态数据Canvas上下文
  823. dynamicCtx.value = uni.createCanvasContext("dynamicCanvas", instance.proxy);
  824. // 初始化十字准心Canvas上下文
  825. crosshairCtx.value = uni.createCanvasContext("crosshairCanvas", instance.proxy);
  826. if (ctx.value) {
  827. // 设置Canvas的内部绘图区域尺寸
  828. ctx.value.canvas = {
  829. width: canvasWidth.value,
  830. height: canvasHeight.value,
  831. };
  832. } else {
  833. console.warn("Canvas上下文未初始化,跳过绘制");
  834. }
  835. // 确保Canvas上下文知道正确的尺寸
  836. if (dynamicCtx.value) {
  837. // 设置Canvas的内部绘图区域尺寸
  838. dynamicCtx.value.canvas = {
  839. width: canvasWidth.value,
  840. height: canvasHeight.value,
  841. };
  842. } else {
  843. console.warn("动态Canvas上下文未初始化,跳过绘制");
  844. }
  845. if (crosshairCtx.value) {
  846. // 设置Canvas的内部绘图区域尺寸
  847. crosshairCtx.value.canvas = {
  848. width: canvasWidth.value,
  849. height: canvasHeight.value,
  850. };
  851. } else {
  852. console.warn("十字准心Canvas上下文未初始化,跳过绘制");
  853. }
  854. // 等待DOM更新
  855. await nextTick();
  856. console.log("ctx", ctx.value);
  857. drawChart();
  858. } catch (error) {
  859. console.error("初始化Canvas失败:", error);
  860. }
  861. };
  862. // 绘制图表主函数-设置基础数据
  863. const drawChart = () => {
  864. if (!ctx.value || !dynamicCtx.value || !crosshairCtx.value) {
  865. console.warn("Canvas上下文未初始化,跳过绘制");
  866. return;
  867. }
  868. const data = klineTab.value == 1 ? timeData.value : klineData.value;
  869. chartRange.value = [];
  870. // 清除画布
  871. // HCharts.setCanvasColor(ctx.value, width, height, CANVAS_BACKGROUND_COLOR);
  872. // HCharts.setCanvasColor(dynamicCtx.value, width, height, CANVAS_BACKGROUND_COLOR);
  873. // HCharts.setCanvasColor(crosshairCtx.value, width, height, CANVAS_BACKGROUND_COLOR);
  874. // 根据当前标签绘制对应图表
  875. if (klineTab.value == 1) {
  876. // 设置标签样式
  877. const label = [
  878. {
  879. text: utils.calculateLabel(data, 1, stockInformation.value.lastDayStockClosePrice, "price", grid[0].horizontalLineNum),
  880. color: [TEXT_COLOR1, TEXT_COLOR1, TEXT_COLOR1, TEXT_COLOR1, TEXT_COLOR2],
  881. fontSize: 12,
  882. lineStyle: ["solid", "solid", "solid", "solid", "solid"],
  883. onlyTwo: false,
  884. },
  885. {
  886. text: utils.calculateLabel(data, 2, stockInformation.value.lastDayStockClosePrice, "volume", grid[1].horizontalLineNum),
  887. color: [TEXT_COLOR1, TEXT_COLOR1],
  888. lineStyle: ["solid", "solid", "solid"],
  889. fontSize: 12,
  890. onlyTwo: true,
  891. },
  892. ];
  893. // 把label加进grid中
  894. grid[0].label = label[0];
  895. grid[1].label = label[1];
  896. drawTimeChart();
  897. } else {
  898. // 设置标签样式
  899. const label = [
  900. {
  901. text: utils.calculateLabel(data, 2, stockInformation.value.lastDayStockClosePrice, "price", grid[0].horizontalLineNum),
  902. color: [TEXT_COLOR1, TEXT_COLOR1, TEXT_COLOR1, TEXT_COLOR1, TEXT_COLOR2],
  903. lineStyle: ["solid", "dash", "dash", "dash", "solid"],
  904. fontSize: 12,
  905. onlyTwo: false,
  906. },
  907. {
  908. text: utils.calculateLabel(data, 2, stockInformation.value.lastDayStockClosePrice, "volume", grid[1].horizontalLineNum),
  909. color: [TEXT_COLOR1, TEXT_COLOR1],
  910. lineStyle: ["solid", "dash", "solid"],
  911. fontSize: 12,
  912. onlyTwo: true,
  913. },
  914. {
  915. text: utils.calculateLabel(data, 2, stockInformation.value.lastDayStockClosePrice, "volume", grid[1].horizontalLineNum),
  916. color: [TEXT_COLOR1, TEXT_COLOR1],
  917. lineStyle: ["solid", "dash", "solid"],
  918. fontSize: 12,
  919. onlyTwo: true,
  920. },
  921. ];
  922. // 把label加进grid中
  923. dayGrid[0].label = label[0];
  924. dayGrid[1].label = label[1];
  925. dayGrid[2].label = label[2];
  926. // HCharts.drawGrid(ctx.value, canvasWidth.value, canvasHeight.value, dayGrid, data[0].date, data[data.length - 1].date);
  927. drawKLineChart();
  928. }
  929. // crosshairCtx.value.draw();
  930. };
  931. const throttledDrawChart = throttle(drawChart, 50);
  932. // // 绘制分时图
  933. const drawTimeChart = () => {
  934. drawCtxChart(grid);
  935. drawDynamicCtxChart();
  936. };
  937. // // 绘制K线图
  938. const drawKLineChart = () => {
  939. drawCtxChart(dayGrid);
  940. drawDynamicCtxChart();
  941. };
  942. const drawCtxChart = (paramGrid) => {
  943. // 检查Canvas上下文是否已初始化
  944. if (!ctx.value) {
  945. console.warn("Canvas上下文未初始化,跳过绘制");
  946. return;
  947. }
  948. // 绘制网格
  949. HCharts.drawGrid(ctx.value, canvasWidth.value, canvasHeight.value, paramGrid, openTime, closeTime);
  950. //执行绘制
  951. ctx.value.draw();
  952. };
  953. const drawDynamicCtxChart = () => {
  954. if (klineTab.value == 1) {
  955. //绘制价格曲线
  956. HCharts.drawPriceLine(dynamicCtx.value, canvasWidth.value, canvasHeight.value, timeData.value, grid, chartRange.value[0]);
  957. //绘制成交量
  958. HCharts.drawVolume(
  959. dynamicCtx.value,
  960. canvasWidth.value,
  961. canvasHeight.value,
  962. timeData.value,
  963. 2,
  964. 240,
  965. grid,
  966. {
  967. max: utils.calculateDataRange(timeData.value, "volume").max,
  968. min: 0,
  969. },
  970. 0
  971. );
  972. HCharts.drawAxisLabels(dynamicCtx.value, canvasWidth.value, canvasHeight.value, grid);
  973. HCharts.drawTopPriceDisplay(crosshairCtx.value, grid, text);
  974. } else {
  975. drawKLine(dynamicCtx.value);
  976. //绘制成交量
  977. HCharts.drawVolume(
  978. dynamicCtx.value,
  979. canvasWidth.value,
  980. canvasHeight.value,
  981. klineData.value,
  982. 2,
  983. klineData.value.length,
  984. dayGrid,
  985. {
  986. max: utils.calculateDataRange(klineData.value, "volume").max,
  987. min: 0,
  988. },
  989. touchState.offset
  990. );
  991. //绘制成交量
  992. HCharts.drawVolume(
  993. dynamicCtx.value,
  994. canvasWidth.value,
  995. canvasHeight.value,
  996. klineData.value,
  997. 3,
  998. klineData.value.length,
  999. dayGrid,
  1000. {
  1001. max: utils.calculateDataRange(klineData.value, "volume").max,
  1002. min: 0,
  1003. },
  1004. touchState.offset
  1005. );
  1006. HCharts.drawAxisLabels(dynamicCtx.value, canvasWidth.value, canvasHeight.value, dayGrid);
  1007. // drawMovingAverage();
  1008. HCharts.drawTopPriceDisplay(crosshairCtx.value, dayGrid, []);
  1009. }
  1010. //执行绘制
  1011. dynamicCtx.value.draw(false);
  1012. crosshairCtx.value.draw();
  1013. };
  1014. const throttledDrawDynamicCtxChart = throttle(drawDynamicCtxChart, 50);
  1015. // const throttledDrawKLineChart = throttle(drawKLineChart, 10);
  1016. // 绘制K线
  1017. const drawKLine = (ctx) => {
  1018. const data = klineData.value;
  1019. if (!data.length) return;
  1020. const width = canvasWidth.value;
  1021. const height = canvasHeight.value;
  1022. // 计算价格范围
  1023. const priceRange = chartRange.value[0];
  1024. const priceDiff = priceRange.max - priceRange.min;
  1025. const areaWidth = (width - dayGrid[0].left - dayGrid[0].right) / data.length;
  1026. const candleWidth = areaWidth * 0.6;
  1027. data.forEach((item, index) => {
  1028. const x = touchState.offset + dayGrid[0].left + (index * (width - dayGrid[0].left - dayGrid[0].right)) / data.length;
  1029. // 计算坐标
  1030. const highY = dayGrid[0].top + (height - dayGrid[0].top - dayGrid[0].bottom) * (1 - (item.high - priceRange.min) / priceDiff);
  1031. const lowY = dayGrid[0].top + (height - dayGrid[0].top - dayGrid[0].bottom) * (1 - (item.low - priceRange.min) / priceDiff);
  1032. const openY = dayGrid[0].top + (height - dayGrid[0].top - dayGrid[0].bottom) * (1 - (item.open - priceRange.min) / priceDiff);
  1033. const closeY = dayGrid[0].top + (height - dayGrid[0].top - dayGrid[0].bottom) * (1 - (item.close - priceRange.min) / priceDiff);
  1034. // 判断涨跌
  1035. const isRise = item.close >= item.open;
  1036. const color = isRise ? "green" : "red";
  1037. // 绘制上下影线
  1038. ctx.setStrokeStyle(color);
  1039. ctx.setLineWidth(1);
  1040. ctx.beginPath();
  1041. ctx.moveTo(x, highY);
  1042. ctx.lineTo(x, lowY);
  1043. ctx.stroke();
  1044. // 绘制K线实体
  1045. const entityTop = isRise ? closeY : openY;
  1046. const entityBottom = isRise ? openY : closeY;
  1047. const entityHeight = Math.max(Math.abs(entityBottom - entityTop), 1);
  1048. ctx.setFillStyle(color);
  1049. ctx.fillRect(x - candleWidth / 2, entityTop, candleWidth, entityHeight);
  1050. });
  1051. };
  1052. // 绘制移动平均线
  1053. const drawMovingAverage = () => {
  1054. const data = klineData.value;
  1055. if (!data.length) return;
  1056. const ma5 = calculateMA(data, 5);
  1057. const ma10 = calculateMA(data, 10);
  1058. drawMALine(ma5, "#fadb14", "MA5"); // 黄色
  1059. drawMALine(ma10, "#eb2f96", "MA10"); // 粉色
  1060. };
  1061. // 计算移动平均线
  1062. const calculateMA = (data, period) => {
  1063. const result = [];
  1064. for (let i = period - 1; i < data.length; i++) {
  1065. let sum = 0;
  1066. for (let j = 0; j < period; j++) {
  1067. sum += data[i - j].close;
  1068. }
  1069. result.push({
  1070. index: i,
  1071. value: sum / period,
  1072. });
  1073. }
  1074. return result;
  1075. };
  1076. // 绘制均线
  1077. const drawMALine = (maData, color, label) => {
  1078. if (!maData.length) return;
  1079. const width = canvasWidth.value;
  1080. const height = canvasHeight.value;
  1081. const data = klineData.value;
  1082. // 计算价格范围
  1083. const highs = data.map((item) => item.high);
  1084. const lows = data.map((item) => item.low);
  1085. const priceRange = chartRange.value[0];
  1086. const priceDiff = priceRange.max - priceRange.min;
  1087. ctx.value.setStrokeStyle(color);
  1088. ctx.value.setLineWidth(1.5);
  1089. ctx.value.beginPath();
  1090. maData.forEach((point, idx) => {
  1091. const x = 40 + (point.index * (width - 60)) / (data.length - 1);
  1092. const y = 20 + (height - 60) * (1 - (point.value - priceRange.min) / priceDiff);
  1093. if (idx === 0) {
  1094. ctx.value.moveTo(x, y);
  1095. } else {
  1096. ctx.value.lineTo(x, y);
  1097. }
  1098. });
  1099. ctx.value.stroke();
  1100. // 绘制图例
  1101. if (maData.length > 0) {
  1102. const lastPoint = maData[maData.length - 1];
  1103. const x = 40 + (lastPoint.index * (width - 60)) / (data.length - 1);
  1104. const y = 20 + (height - 60) * (1 - (lastPoint.value - priceRange.min) / priceDiff);
  1105. HCharts.drawText(ctx.value`${label}: ${utils.formatPrice(lastPoint.value)}`, x + 10, y - 5, 12, color);
  1106. }
  1107. };
  1108. // 触摸事件处理
  1109. const touchStart = (e) => {
  1110. e.preventDefault(); // 阻止页面滚动等默认行为
  1111. if (typeof e.touches[1] === "undefined") {
  1112. touchState.startX = e.touches[0].x;
  1113. touchState.startY = e.touches[0].y;
  1114. touchState.isMoving = false;
  1115. } else if (typeof e.touches[1] !== "undefined" && !crosshair.show) {
  1116. // touchState.startX1 = e.touches[0].x;
  1117. // touchState.startY1 = e.touches[0].y;
  1118. // touchState.startX2 = e.touches[1].x;
  1119. // touchState.startY2 = e.touches[1].y;
  1120. // touchState.isMoving = false;
  1121. }
  1122. };
  1123. const touchMove = (e) => {
  1124. touchState.isMoving = true;
  1125. // 计算移动距离
  1126. const currentX = e.touches[0].x;
  1127. const currentY = e.touches[0].y;
  1128. const deltaX = currentX - touchState.startX;
  1129. const deltaY = currentY - touchState.startY;
  1130. touchState.moveDistance = Math.max(touchState.moveDistance, Math.sqrt(deltaX * deltaX + deltaY * deltaY));
  1131. if (crosshair.show) {
  1132. if (isInChartArea(currentX, currentY, klineTab.value === 1 ? grid : dayGrid)) {
  1133. throttledUpdateCrosshair(currentX, currentY);
  1134. } else {
  1135. // 如果移出图表区域,隐藏十字准线
  1136. // crosshair.show = false;
  1137. if (klineTab.value === 1) {
  1138. HCharts.drawCrosshair(crosshairCtx.value, canvasWidth.value, canvasHeight.value, grid, crosshair, text);
  1139. } else {
  1140. HCharts.drawCrosshair(crosshairCtx.value, canvasWidth.value, canvasHeight.value, dayGrid, crosshair, []);
  1141. }
  1142. }
  1143. } else {
  1144. if (klineTab.value === 2) {
  1145. // if(currentY)
  1146. if (currentX < touchState.startX) {
  1147. touchState.offset += currentX - touchState.startX;
  1148. throttledDrawDynamicCtxChart();
  1149. touchState.startX = currentX;
  1150. } else {
  1151. touchState.offset += currentX - touchState.startX;
  1152. throttledDrawDynamicCtxChart();
  1153. touchState.startX = currentX;
  1154. }
  1155. if (canvasWidth.value + touchState.offset < 30) {
  1156. touchState.offset = 0;
  1157. }
  1158. }
  1159. }
  1160. };
  1161. const touchEnd = (e) => {
  1162. // 触摸结束,隐藏十字准线
  1163. if (touchState.moveDistance < touchState.moveThreshold) {
  1164. // 移动距离小于阈值,认为是点击事件
  1165. crosshair.show = !crosshair.show;
  1166. }
  1167. if (crosshair.show) {
  1168. const currentX = e.changedTouches[0].x;
  1169. const currentY = e.changedTouches[0].y;
  1170. if (isInChartArea(currentX, currentY, klineTab.value === 1 ? grid : dayGrid)) {
  1171. throttledUpdateCrosshair(currentX, currentY);
  1172. }
  1173. }
  1174. if (klineTab.value === 1) {
  1175. HCharts.drawCrosshair(crosshairCtx.value, canvasWidth.value, canvasHeight.value, grid, crosshair, text);
  1176. } else {
  1177. HCharts.drawCrosshair(crosshairCtx.value, canvasWidth.value, canvasHeight.value, dayGrid, crosshair, []);
  1178. }
  1179. // 重置移动距离
  1180. touchState.moveDistance = 0;
  1181. };
  1182. // 检查坐标是否在图表区域内
  1183. const isInChartArea = (x, y, grid) => {
  1184. const width = canvasWidth.value;
  1185. const height = canvasHeight.value;
  1186. if (x < grid[0].left || x > width - grid[0].right) return false;
  1187. for (let i = 0; i < grid.length; i++) {
  1188. if (y >= grid[i].top && y <= height - grid[i].bottom) return true;
  1189. }
  1190. return false;
  1191. };
  1192. // 更新十字准线位置和数据
  1193. const updateCrosshair = (x, y) => {
  1194. if (!crosshair.show) return;
  1195. // 更新Y坐标以匹配实际价格
  1196. const data = klineTab.value === 1 ? timeData.value : klineData.value;
  1197. const width = canvasWidth.value;
  1198. const height = canvasHeight.value;
  1199. crosshair.x = x;
  1200. crosshair.y = y;
  1201. const nearestData = utils.findNearestDataPoint(x, klineTab.value === 1 ? 240 : data.length, data, klineTab.value === 1 ? grid : dayGrid, klineTab.value === 1 ? 0 : touchState.offset);
  1202. crosshair.x = nearestData.x;
  1203. stockInformation.value.currentPrice = nearestData.price || nearestData.close;
  1204. stockInformation.value.volume = nearestData.volume;
  1205. // 涨跌额度
  1206. if (klineTab.value == 1) {
  1207. stockInformation.value.currentValue = stockInformation.value.currentPrice - stockInformation.value.lastDayStockClosePrice;
  1208. stockInformation.value.currentRatio = ((stockInformation.value.currentPrice - stockInformation.value.lastDayStockClosePrice) / stockInformation.value.lastDayStockClosePrice) * 100;
  1209. } else {
  1210. stockInformation.value.openPrice = nearestData.open;
  1211. stockInformation.value.highPrice = nearestData.high;
  1212. stockInformation.value.lowPrice = nearestData.low;
  1213. if (nearestData.index != 0) {
  1214. stockInformation.value.lastDayStockClosePrice = data[nearestData.index - 1].close;
  1215. stockInformation.value.currentValue = stockInformation.value.currentPrice - stockInformation.value.lastDayStockClosePrice;
  1216. stockInformation.value.currentRatio = ((stockInformation.value.currentPrice - stockInformation.value.lastDayStockClosePrice) / stockInformation.value.lastDayStockClosePrice) * 100;
  1217. }
  1218. }
  1219. if (klineTab.value === 1 && crosshair.snapToData) {
  1220. // 吸附到最近的数据点
  1221. if (nearestData) {
  1222. crosshair.currentData = nearestData;
  1223. const priceDiff = chartRange.value[0].max - chartRange.value[0].min;
  1224. crosshair.y = grid[0].top + (height - grid[0].bottom - grid[0].top) * (1 - (nearestData.price - chartRange.value[0].min) / priceDiff);
  1225. }
  1226. } else {
  1227. // 自由移动模式
  1228. const currentPrice = utils.calculatePriceFromY(y, data, klineTab.value === 1 ? grid : dayGrid);
  1229. crosshair.currentData = {
  1230. ...nearestData,
  1231. price: currentPrice,
  1232. };
  1233. }
  1234. if (crosshair?.currentData?.volume) {
  1235. text[0][1].value = crosshair.currentData.price;
  1236. text[1][0].value = crosshair.currentData.volume;
  1237. }
  1238. // 只重绘十字准心,不重绘整个图表
  1239. if (klineTab.value === 1) {
  1240. HCharts.drawCrosshair(crosshairCtx.value, canvasWidth.value, canvasHeight.value, grid, crosshair, text);
  1241. } else {
  1242. HCharts.drawCrosshair(crosshairCtx.value, canvasWidth.value, canvasHeight.value, dayGrid, crosshair, []);
  1243. }
  1244. };
  1245. const throttledUpdateCrosshair = throttle(updateCrosshair, 10);
  1246. // 缩放控制函数
  1247. const zoomIn = () => {
  1248. touchState.scale = Math.min(touchState.maxScale, touchState.scale * 1.2);
  1249. drawChart();
  1250. };
  1251. const zoomOut = () => {
  1252. touchState.scale = Math.max(touchState.minScale, touchState.scale / 1.2);
  1253. drawChart();
  1254. };
  1255. // 监听数据变化
  1256. // watch([timeData, klineData], () => {
  1257. // console.log("数据变化");
  1258. // drawChart();
  1259. // });
  1260. watch(klineTab, () => {
  1261. console.log("标签页变化");
  1262. drawChart();
  1263. });
  1264. /*
  1265. const connectTcp = (ip, port) => {
  1266. console.log(`🚀 正在连接TCP服务器 ${ip}:${port}...`);
  1267. TCPSocket.connect(
  1268. {
  1269. channel: "1",
  1270. ip: ip,
  1271. port: port,
  1272. },
  1273. (result) => {
  1274. console.log(result);
  1275. if (result.status == 0) {
  1276. tcpObject.isConnected = true;
  1277. console.log("tcp连接成功");
  1278. } else if (result.status == 1) {
  1279. tcpObject.isConnected = false;
  1280. console.log("tcp断开连接");
  1281. }
  1282. if (result.receivedMsg) {
  1283. console.log("收到服务器发送的数据", result.receivedMsg);
  1284. if (result.receivedMsg.length == 0 || result.receivedMsg.includes("欢迎")) {
  1285. resultR.value = [];
  1286. } else {
  1287. const msgPacket = JSON.parse(result.receivedMsg);
  1288. resultR.value.push(msgPacket);
  1289. // 股票代码
  1290. if (msgPacket.stock_code) {
  1291. stockInformation.value.stockCode = msgPacket.stock_code;
  1292. }
  1293. // 股票名称
  1294. if (msgPacket.stock_name) {
  1295. stockInformation.value.stockName = msgPacket.stock_name;
  1296. }
  1297. // 前一日收盘价
  1298. if (msgPacket.pre_close) {
  1299. stockInformation.value.lastDayStockClosePrice = msgPacket.pre_close;
  1300. }
  1301. // 当前股价(收盘价)
  1302. if (msgPacket.current_price) {
  1303. stockInformation.value.currentPrice = msgPacket.current_price;
  1304. }
  1305. // 涨跌额度
  1306. if (msgPacket.current_price && msgPacket.pre_close) {
  1307. stockInformation.value.currentValue = msgPacket.current_price - msgPacket.pre_close;
  1308. stockInformation.value.currentRatio = ((msgPacket.current_price - msgPacket.pre_close) / msgPacket.pre_close) * 100;
  1309. }
  1310. // 最高价
  1311. if (msgPacket.high_price) {
  1312. stockInformation.value.highPrice = msgPacket.high_price;
  1313. }
  1314. // 最低价
  1315. if (msgPacket.close_price) {
  1316. stockInformation.value.lowPrice = msgPacket.close_price;
  1317. }
  1318. // 开盘价
  1319. if (msgPacket.open_price) {
  1320. stockInformation.value.openPrice = msgPacket.open_price;
  1321. }
  1322. // 开盘价
  1323. if (msgPacket.low_price) {
  1324. stockInformation.value.lowPrice = msgPacket.low_price;
  1325. }
  1326. // 收盘价(当前股价)
  1327. if (msgPacket.current_price) {
  1328. stockInformation.value.closePrice = msgPacket.current_price;
  1329. }
  1330. // 成交量
  1331. if (msgPacket.volume) {
  1332. stockInformation.value.volume = msgPacket.volume;
  1333. }
  1334. // 成交量比
  1335. if (msgPacket.volume_ratio) {
  1336. stockInformation.value.volumeRatio = msgPacket.volume_ratio;
  1337. }
  1338. // 成交额
  1339. if (msgPacket.amount) {
  1340. stockInformation.value.amount = msgPacket.amount;
  1341. }
  1342. // 市盈
  1343. if (msgPacket.market_earn) {
  1344. stockInformation.value.marketEarn = msgPacket.market_earn;
  1345. }
  1346. // 换手率
  1347. if (msgPacket.turnover_ratio) {
  1348. stockInformation.value.turnoverRatio = msgPacket.turnover_ratio;
  1349. }
  1350. // 市值
  1351. if (msgPacket.total_market_value) {
  1352. stockInformation.value.marketValue = msgPacket.total_market_value;
  1353. }
  1354. }
  1355. }
  1356. // if (result.receivedHexMsg) {
  1357. // //服务器返回16进制数据
  1358. // console.log("📥 收到16进制数据:", result.receivedHexMsg);
  1359. // let msg = result.receivedHexMsg;
  1360. // let sum = msg.length / 2;
  1361. // let arr = [];
  1362. // for (let k = 0; k < sum; k++) {
  1363. // let i = msg.substring(k * 2, k * 2 + 2);
  1364. // arr.push(i);
  1365. // }
  1366. // console.log("转换成16进制数组:", arr);
  1367. // if (tcpObject.responseCallback) {
  1368. // tcpObject.responseCallback({
  1369. // data: arr,
  1370. // });
  1371. // }
  1372. // }
  1373. // 设置连接超时
  1374. setTimeout(() => {
  1375. if (!tcpObject.isConnected) {
  1376. throw new Error("连接超时");
  1377. return;
  1378. }
  1379. }, TIME_OUT);
  1380. }
  1381. );
  1382. };
  1383. // 断开连接
  1384. const disconnect = () => {
  1385. try {
  1386. TCPSocket.disconnect({
  1387. channel: "1",
  1388. });
  1389. tcpObject.isConnected = false;
  1390. console.log("✅ 连接已关闭");
  1391. } catch (e) {
  1392. console.log("⚠️ 断开连接时发生错误:", e.message);
  1393. }
  1394. };
  1395. const startTcp = async () => {
  1396. console.log("🚀 TCP客户端启动");
  1397. console.log(`目标服务器: ${tcpObject.ip}:${tcpObject.port}`);
  1398. try {
  1399. // 连接服务器
  1400. await connectTcp(tcpObject.ip, tcpObject.port);
  1401. } catch (e) {
  1402. console.log("error", e);
  1403. }
  1404. };
  1405. */
  1406. // 定时器标识(用于清除定时器)
  1407. let timer = null;
  1408. let index = 0;
  1409. // 定时添加数据的函数
  1410. const startAddDataTimer = () => {
  1411. if (timer) {
  1412. console.log("存在旧定时器,卸载旧定时器");
  1413. clearInterval(timer);
  1414. }
  1415. console.log("开始定时任务");
  1416. // 每隔5秒执行一次
  1417. timer = setInterval(() => {
  1418. if (index < testTimeData.length) {
  1419. timeData.value.push(testTimeData[index]);
  1420. console.log("新增数据:", testTimeData[index]);
  1421. // 触发图表重新绘制
  1422. drawChart();
  1423. index++;
  1424. } else {
  1425. clearInterval(timer);
  1426. }
  1427. }, 2000); // 5000毫秒 = 5秒
  1428. };
  1429. // 保存定时器,用于页面卸载时清理
  1430. onUnmounted(() => {
  1431. // disconnect();
  1432. if (timer) {
  1433. console.log("卸载定时器");
  1434. clearInterval(timer);
  1435. }
  1436. });
  1437. onMounted(async () => {
  1438. // 获取系统信息,处理高清屏
  1439. const systemInfo = uni.getSystemInfoSync();
  1440. pixelRatio.value = systemInfo.pixelRatio;
  1441. // 设置Canvas实际像素(考虑pixelRatio以获得高清效果)
  1442. // 1rpx = 设备屏幕宽度 / 750
  1443. const rpxToPx = systemInfo.windowWidth / 750;
  1444. const offsetHeight = (150 + 200 + 80 + 150 + 30) * rpxToPx; // 350rpx转换为px
  1445. const calculatedHeight = systemInfo.windowHeight - offsetHeight;
  1446. canvasWidth.value = systemInfo.windowWidth;
  1447. canvasHeight.value = Math.max(calculatedHeight, canvasHeight.value);
  1448. // startTcp();
  1449. // timeData.value = testTimeData;
  1450. timeData.value = testTimeData.slice(0, 100);
  1451. klineData.value = testKlineData;
  1452. // klineData.value = testKlineData.slice(-touchState.baseVisibleCount);
  1453. // 前一日收盘价
  1454. let prevClosePrice = timeData.value[timeData.value.length - 2].price || stockInformation.value.closePrice;
  1455. stockInformation.value.lastDayStockClosePrice = prevClosePrice;
  1456. // 当前股价
  1457. stockInformation.value.currentPrice = timeData.value[timeData.value.length - 1].price;
  1458. // 涨跌额度
  1459. stockInformation.value.currentValue = stockInformation.value.currentPrice - stockInformation.value.lastDayStockClosePrice;
  1460. // 涨跌幅度
  1461. stockInformation.value.currentRatio = ((stockInformation.value.currentPrice - stockInformation.value.lastDayStockClosePrice) / stockInformation.value.lastDayStockClosePrice) * 100;
  1462. // 成交量
  1463. stockInformation.value.volume = timeData.value[timeData.value.length - 1].volume;
  1464. text[0][1].value = utils.formatPrice(stockInformation.value.currentPrice);
  1465. text[1][0].value = utils.formatStockNumber(stockInformation.value.volume);
  1466. await nextTick();
  1467. setTimeout(() => {
  1468. initCanvas();
  1469. }, 200);
  1470. });
  1471. </script>
  1472. <style>
  1473. .container {
  1474. width: 100%;
  1475. min-height: 100vh;
  1476. background-color: #f6f6f6;
  1477. }
  1478. .title-container {
  1479. width: 100%;
  1480. height: 150rpx;
  1481. background-color: white;
  1482. display: flex;
  1483. flex-direction: column;
  1484. justify-content: flex-end;
  1485. }
  1486. .title {
  1487. /* border: 1px solid #ff0000; */
  1488. position: relative;
  1489. /* 关键:作为绝对定位的父容器 */
  1490. width: 100%;
  1491. height: 80rpx;
  1492. display: flex;
  1493. justify-content: center;
  1494. align-items: center;
  1495. }
  1496. .back-homepage-btn {
  1497. margin-left: 40rpx;
  1498. margin-right: auto;
  1499. height: 30rpx;
  1500. width: 20rpx;
  1501. z-index: 1;
  1502. }
  1503. .mid-title {
  1504. position: absolute;
  1505. left: 0;
  1506. right: 0;
  1507. display: flex;
  1508. justify-content: center;
  1509. align-items: center;
  1510. }
  1511. .left-page {
  1512. height: 40rpx;
  1513. width: 40rpx;
  1514. }
  1515. .right-page {
  1516. height: 40rpx;
  1517. width: 40rpx;
  1518. }
  1519. .stock-id {
  1520. margin: 0rpx 40rpx;
  1521. display: flex;
  1522. flex-direction: column;
  1523. text-align: center;
  1524. }
  1525. .stock-name {
  1526. font-weight: bold;
  1527. }
  1528. .stock-code {
  1529. font-size: 0.8rem;
  1530. font-weight: bold;
  1531. color: #a1a1a1;
  1532. }
  1533. .search {
  1534. height: 40rpx;
  1535. width: 40rpx;
  1536. }
  1537. .more {
  1538. height: 100%;
  1539. display: flex;
  1540. justify-content: center;
  1541. align-items: center;
  1542. margin-right: 40rpx;
  1543. margin-left: 20rpx;
  1544. }
  1545. .body {
  1546. overflow: auto;
  1547. height: calc(100vh - 305rpx);
  1548. /* border: 1px solid red; */
  1549. }
  1550. .stock-information {
  1551. background-color: white;
  1552. width: 100%;
  1553. height: 200rpx;
  1554. margin: 10rpx 0rpx;
  1555. display: flex;
  1556. align-items: center;
  1557. position: relative;
  1558. /* 为伪元素定位做准备 */
  1559. }
  1560. /* 右下角黑色三角形 */
  1561. .stock-information::after {
  1562. content: "";
  1563. position: absolute;
  1564. bottom: 0;
  1565. right: 0;
  1566. width: 0;
  1567. height: 0;
  1568. border-left: 20rpx solid transparent;
  1569. border-bottom: 20rpx solid #6a6a6a;
  1570. }
  1571. .stock-detail-container {
  1572. position: absolute;
  1573. top: 100%;
  1574. /* 在父容器下方 */
  1575. left: 0;
  1576. /* 从左边开始 */
  1577. right: 0;
  1578. /* 到右边结束 */
  1579. width: 100%;
  1580. /* height: 300rpx; 使用固定高度替代calc,避免计算问题 */
  1581. height: calc(100vh - 515rpx);
  1582. display: flex;
  1583. flex-direction: column;
  1584. background-color: rgba(0, 0, 0, 0.6);
  1585. z-index: 100;
  1586. box-sizing: border-box;
  1587. pointer-events: auto;
  1588. }
  1589. .stock-detail {
  1590. border: 1px solid #cacaca;
  1591. width: 100%;
  1592. display: flex;
  1593. background-color: white;
  1594. padding: 10rpx 0;
  1595. }
  1596. .first-column,
  1597. .second-column {
  1598. width: 50%;
  1599. height: 100%;
  1600. display: flex;
  1601. flex-direction: column;
  1602. color: #6a6a6a;
  1603. font-size: 0.8rem;
  1604. }
  1605. .first-column-data,
  1606. .second-column-data {
  1607. display: flex;
  1608. justify-content: space-between;
  1609. align-items: center;
  1610. padding: 10rpx 40rpx;
  1611. }
  1612. .stock-detail-title {
  1613. color: #6a6a6a;
  1614. }
  1615. .stock-detail-value {
  1616. color: black;
  1617. }
  1618. .price-up {
  1619. color: #10b981;
  1620. }
  1621. .price-down {
  1622. color: #ef4444;
  1623. }
  1624. .price-none {
  1625. color: black;
  1626. }
  1627. .stock-current-data {
  1628. width: 30%;
  1629. height: 70%;
  1630. display: flex;
  1631. flex-direction: column;
  1632. }
  1633. .stock-current-price {
  1634. font-weight: bold;
  1635. font-size: 1.2rem;
  1636. width: 100%;
  1637. height: 50%;
  1638. display: flex;
  1639. justify-content: center;
  1640. align-items: center;
  1641. }
  1642. .stock-current-other {
  1643. width: 100%;
  1644. height: 50%;
  1645. display: flex;
  1646. font-weight: bold;
  1647. font-size: 0.6rem;
  1648. }
  1649. .stock-current-value {
  1650. width: 50%;
  1651. height: 100%;
  1652. display: flex;
  1653. justify-content: center;
  1654. align-items: center;
  1655. }
  1656. .stock-current-ratio {
  1657. width: 50%;
  1658. height: 100%;
  1659. display: flex;
  1660. justify-content: center;
  1661. align-items: center;
  1662. }
  1663. .stock-other-data {
  1664. height: 100%;
  1665. width: 70%;
  1666. display: flex;
  1667. flex-direction: column;
  1668. }
  1669. .first-line,
  1670. .second-line,
  1671. .third-line {
  1672. display: flex;
  1673. align-items: center;
  1674. width: 100%;
  1675. height: 33%;
  1676. /* font-weight: bold; */
  1677. font-size: 0.8rem;
  1678. }
  1679. .value {
  1680. margin-left: auto;
  1681. margin-right: 20rpx;
  1682. }
  1683. .high-price,
  1684. .volume,
  1685. .volume-ratio,
  1686. .low-price,
  1687. .amount,
  1688. .market-earn,
  1689. .open-price,
  1690. .turnover-ratio,
  1691. .market-value {
  1692. display: flex;
  1693. flex: 1;
  1694. }
  1695. .stock-chart {
  1696. width: 100%;
  1697. }
  1698. .stock-kline-tab {
  1699. display: flex;
  1700. width: 100%;
  1701. height: 80rpx;
  1702. /* border: 1px solid black; */
  1703. }
  1704. .tab-day,
  1705. .tab-month,
  1706. .tab-time,
  1707. .tab-week,
  1708. .tab-more,
  1709. .tab-setting {
  1710. display: flex;
  1711. justify-content: center;
  1712. align-items: center;
  1713. flex: 1;
  1714. font-size: 0.8rem;
  1715. color: #6a6a6a;
  1716. position: relative;
  1717. }
  1718. /* 向下小三角样式 */
  1719. .arrow-down {
  1720. width: 0;
  1721. height: 0;
  1722. border-left: 10rpx solid transparent;
  1723. border-right: 10rpx solid transparent;
  1724. border-bottom: 12rpx solid currentColor;
  1725. margin-left: 8rpx;
  1726. display: inline-block;
  1727. }
  1728. .arrow-up {
  1729. width: 0;
  1730. height: 0;
  1731. border-left: 10rpx solid transparent;
  1732. border-right: 10rpx solid transparent;
  1733. border-top: 12rpx solid currentColor;
  1734. margin-left: 8rpx;
  1735. display: inline-block;
  1736. }
  1737. .moreTabsContainer {
  1738. width: 100%;
  1739. display: flex;
  1740. gap: 5rpx;
  1741. margin-bottom: 5rpx;
  1742. }
  1743. .moreTabItem {
  1744. flex: 1;
  1745. padding: 10rpx 20rpx;
  1746. border-radius: 10rpx;
  1747. background-color: white;
  1748. font-size: 0.85rem;
  1749. color: #6a6a6a;
  1750. text-align: center;
  1751. }
  1752. .tab-selected {
  1753. color: #db1f1d;
  1754. }
  1755. .tab-selected::after {
  1756. content: "";
  1757. position: absolute;
  1758. bottom: 10rpx;
  1759. left: 50%;
  1760. transform: translateX(-50%);
  1761. width: 40rpx;
  1762. height: 5rpx;
  1763. background-color: #db1f1d;
  1764. }
  1765. .tab-setting-img {
  1766. width: 30rpx;
  1767. height: 30rpx;
  1768. }
  1769. .time-chart-container {
  1770. width: 100%;
  1771. min-height: 400rpx;
  1772. background-color: #ffffff;
  1773. box-sizing: border-box;
  1774. }
  1775. .stock-chart {
  1776. display: flex;
  1777. flex-direction: column;
  1778. align-items: center;
  1779. }
  1780. .kline-chart-container {
  1781. width: 100%;
  1782. height: 400rpx;
  1783. background-color: #ffffff;
  1784. padding: 20rpx;
  1785. box-sizing: border-box;
  1786. display: flex;
  1787. justify-content: center;
  1788. align-items: center;
  1789. }
  1790. .bottomTool {
  1791. width: 100%;
  1792. height: 150rpx;
  1793. position: fixed;
  1794. bottom: 0;
  1795. background-color: white;
  1796. display: flex;
  1797. box-shadow: 0 -4px 12px rgba(0, 0, 0, 0.1);
  1798. }
  1799. .index,
  1800. .function,
  1801. .favorites {
  1802. flex: 1;
  1803. display: flex;
  1804. justify-content: center;
  1805. align-items: center;
  1806. flex-direction: column;
  1807. font-size: 12px;
  1808. transition: all 0.2s ease;
  1809. }
  1810. .index:active,
  1811. .function:active,
  1812. .favorites:active {
  1813. background-color: rgba(99, 99, 99, 0.5);
  1814. transform: scale(0.95);
  1815. transition: all 0.1s ease;
  1816. }
  1817. .icon {
  1818. width: 40rpx;
  1819. height: 40rpx;
  1820. }
  1821. </style>