Blame view

components/uni-charts/uni-charts.vue 11.7 KB
4f475013   刘淇   k线图
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
  <template>
    <view class="uni-charts">
      <canvas
          v-if="type !== 'map'"
          class="charts-canvas"
          :style="{width: width + 'px', height: height + 'px'}"
          canvas-id="uni-charts"
          @touchstart="touchStart"
          @touchmove="touchMove"
          @touchend="touchEnd"
      ></canvas>
      <view v-else class="map-container" :style="{width: width + 'px', height: height + 'px'}">
        <slot name="map"></slot>
      </view>
    </view>
  </template>
  
  <script>
  export default {
    name: 'uniCharts',
    props: {
      type: {
        type: String,
        default: 'line'
      },
      data: {
        type: Array,
        default () {
          return []
        }
      },
      categories: {
        type: Array,
        default () {
          return []
        }
      },
      option: {
        type: Object,
        default () {
          return {}
        }
      },
      width: {
        type: [Number, String],
        default: 375
      },
      height: {
        type: [Number, String],
        default: 200
      }
    },
    data () {
      return {
        ctx: null,
        chartData: {},
        touchInfo: {}
      }
    },
    watch: {
      data: {
        deep: true,
        handler () {
          this.initChart()
        }
      },
      categories: {
        deep: true,
        handler () {
          this.initChart()
        }
      },
      option: {
        deep: true,
        handler () {
          this.initChart()
        }
      }
    },
    mounted () {
      this.initChart()
    },
    methods: {
      initChart () {
        if (this.type === 'kline') {
          this.drawKline()
        } else if (this.type === 'line') {
          this.drawLine()
        }
      },
cf70629b   刘淇   养护计划 照片 自己写样式
91
      // 折线图绘制(移除平滑过渡,改为纯直线)
4f475013   刘淇   k线图
92
93
94
95
96
97
98
99
100
101
102
      drawLine () {
        if (!this.data.length || !this.categories.length) return;
  
        const ctx = uni.createCanvasContext('uni-charts', this)
        this.ctx = ctx
        const { width, height } = this
        const {
          grid = {},
          xAxis = {},
          yAxis = {},
          legend = {},
cf70629b   刘淇   养护计划 照片 自己写样式
103
          color = ['#25AF69', '#B34C17']
4f475013   刘淇   k线图
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
        } = this.option
  
        // 清空画布
        ctx.clearRect(0, 0, width, height)
  
        // 调整Grid布局,彻底解决重叠
        const gridTop = grid.top ? (typeof grid.top === 'string' ? parseFloat(grid.top) / 100 * height : grid.top) : 60
        const gridLeft = grid.left ? (typeof grid.left === 'string' ? parseFloat(grid.left) / 100 * width : grid.left) : 70
        const gridRight = grid.right ? (typeof grid.right === 'string' ? parseFloat(grid.right) / 100 * width : grid.right) : 20
        const gridBottom = grid.bottom ? (typeof grid.bottom === 'string' ? parseFloat(grid.bottom) / 100 * height : grid.bottom) : 50
  
        const drawWidth = width - gridLeft - gridRight
        const drawHeight = height - gridTop - gridBottom
  
        // Y轴最大值自适应(无小数点)
        let allValues = []
        this.data.forEach(series => {
          allValues = allValues.concat(series.data)
        })
        if (allValues.length === 0) return;
  
        // 动态计算Y轴极值(保留10%顶部余量,转为整数)
        const rawMaxVal = Math.max(...allValues)
        const rawMinVal = Math.min(...allValues)
        const maxVal = yAxis.max || Math.ceil(rawMaxVal * 1.1) // 向上取整,保证能容纳最大值
        const minVal = yAxis.min || (rawMinVal < 0 ? Math.floor(rawMinVal * 1.1) : 0) // 向下取整(负数),默认0
        const valRange = maxVal - minVal || 1
  
        // 计算X轴每个点的宽度
        const xStep = drawWidth / (this.categories.length - 1 || 1)
  
        // X轴标签防拥挤
        const minLabelWidth = 30
        const maxShowLabels = Math.floor(drawWidth / minLabelWidth)
        const labelInterval = maxShowLabels < this.categories.length
            ? Math.ceil(this.categories.length / maxShowLabels)
            : 1
  
        // 绘制网格线 + Y轴整数刻度
        ctx.setStrokeStyle(yAxis.splitLine?.lineStyle?.color || '#f5f5f7')
        ctx.setLineWidth(1)
        const yTickCount = 5
        const yTickStep = valRange / yTickCount
  
        for (let i = 0; i <= yTickCount; i++) {
          const y = gridTop + drawHeight - (i * drawHeight / yTickCount)
          // 绘制网格线
          ctx.beginPath()
          ctx.moveTo(gridLeft, y)
          ctx.lineTo(width - gridRight, y)
          ctx.stroke()
  
cf70629b   刘淇   养护计划 照片 自己写样式
156
          // Y轴显示整数(无小数点)
4f475013   刘淇   k线图
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
          ctx.setFillStyle(yAxis.axisLabel?.color || '#666')
          ctx.setFontSize(yAxis.axisLabel?.fontSize || 12)
          const val = minVal + (i * yTickStep)
          // 转为整数(四舍五入),彻底去掉小数点
          const intVal = Math.round(val)
          let valText = intVal.toString()
          // 长数字处理(仍为整数格式)
          if (valText.length > 6) {
            valText = intVal.toLocaleString() // 用千分位显示长整数,如 1234567 → 1,234,567
          }
          // 文字右对齐,避免折叠
          const textWidth = ctx.measureText(valText).width
          ctx.fillText(valText, gridLeft - 10 - textWidth, y + 5)
        }
  
        // 绘制X轴标签
        ctx.setFillStyle(xAxis.axisLabel?.color || '#666')
        ctx.setFontSize(xAxis.axisLabel?.fontSize || 12)
        this.categories.forEach((text, index) => {
          if (index % labelInterval === 0) {
            const x = gridLeft + index * xStep
            let labelText = text
            if (text.length > 6) {
              labelText = text.slice(0, 6) + '...'
            }
            const textLines = labelText.split('\n')
  
            textLines.forEach((line, lineIdx) => {
              const textWidth = ctx.measureText(line).width
              ctx.fillText(line, x - textWidth / 2, height - gridBottom + 20 + (lineIdx * 12))
            })
          }
        })
  
        // 优化图例间距
        if (legend.show) {
          ctx.setFontSize(legend.textStyle?.fontSize || 12)
          let legendX = gridLeft + 10
          this.data.forEach((series, idx) => {
            let seriesName = series.name || `系列${idx + 1}`
            if (seriesName.length > 8) {
              seriesName = seriesName.slice(0, 8) + '...'
            }
            const textWidth = ctx.measureText(seriesName).width
            const legendItemWidth = textWidth + 25
  
            const legendY = gridTop - 30
            ctx.setFillStyle(series.color || color[idx % color.length])
            ctx.fillRect(legendX, legendY, 10, 10)
            ctx.setFillStyle('#666')
            ctx.fillText(seriesName, legendX + 15, legendY + 8)
  
            legendX += Math.max(80, legendItemWidth + 10)
          })
        }
  
cf70629b   刘淇   养护计划 照片 自己写样式
213
        // ========== 核心修改:移除平滑曲线,改为纯直线连接 ==========
4f475013   刘淇   k线图
214
215
216
217
218
219
220
221
222
223
224
225
226
227
        this.data.forEach((series, seriesIdx) => {
          const seriesColor = series.color || color[seriesIdx % color.length]
  
          ctx.setStrokeStyle(seriesColor)
          ctx.setLineWidth(2)
          ctx.beginPath()
  
          series.data.forEach((value, index) => {
            const x = gridLeft + index * xStep
            const y = gridTop + drawHeight - ((value - minVal) / valRange) * drawHeight
  
            if (index === 0) {
              ctx.moveTo(x, y)
            } else {
cf70629b   刘淇   养护计划 照片 自己写样式
228
229
              // 直接直线连接,移除所有贝塞尔曲线平滑逻辑
              ctx.lineTo(x, y)
4f475013   刘淇   k线图
230
231
232
233
234
235
236
237
            }
          })
  
          ctx.stroke()
        })
  
        ctx.draw()
      },
cf70629b   刘淇   养护计划 照片 自己写样式
238
      // K线图绘制(同步修改Y轴为整数,K线本身无平滑逻辑,保持原样)
4f475013   刘淇   k线图
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
      drawKline () {
        const ctx = uni.createCanvasContext('uni-charts', this)
        this.ctx = ctx
        const { width, height } = this
        const { grid = {}, xAxis = {}, yAxis = {}, color = ['#B34C17', '#25AF69'] } = this.option
  
        ctx.clearRect(0, 0, width, height)
  
        // 调整Grid布局
        const gridTop = grid.top ? (typeof grid.top === 'string' ? parseFloat(grid.top) / 100 * height : grid.top) : 50
        const gridLeft = grid.left ? (typeof grid.left === 'string' ? parseFloat(grid.left) / 100 * width : grid.left) : 70
        const gridRight = grid.right ? (typeof grid.right === 'string' ? parseFloat(grid.right) / 100 * width : grid.right) : 20
        const gridBottom = grid.bottom ? (typeof grid.bottom === 'string' ? parseFloat(grid.bottom) / 100 * height : grid.bottom) : 40
  
        const drawWidth = width - gridLeft - gridRight
        const drawHeight = height - gridTop - gridBottom
  
        // Y轴自适应极值(整数)
        let allValues = []
        this.data.forEach(item => {
          allValues = allValues.concat([item.open, item.high, item.low, item.close])
        })
        if (allValues.length === 0) return;
  
        const rawMaxVal = Math.max(...allValues)
        const rawMinVal = Math.min(...allValues)
        const maxVal = yAxis.max || Math.ceil(rawMaxVal * 1.1)
        const minVal = yAxis.min || (rawMinVal < 0 ? Math.floor(rawMinVal * 1.1) : 0)
        const valRange = maxVal - minVal || 1
  
        const xStep = drawWidth / (this.data.length || 1)
  
        // 绘制网格线和Y轴整数刻度
        ctx.setStrokeStyle('#f5f5f7')
        ctx.setLineWidth(1)
        const yTickCount = 5
        for (let i = 0; i <= yTickCount; i++) {
          const y = gridTop + drawHeight - (i * drawHeight / yTickCount)
          ctx.beginPath()
          ctx.moveTo(gridLeft, y)
          ctx.lineTo(width - gridRight, y)
          ctx.stroke()
  
          // Y轴显示整数
          ctx.setFillStyle(yAxis.axisLabel?.color || '#666')
          ctx.setFontSize(yAxis.axisLabel?.fontSize || 12)
          const val = minVal + (i * valRange / yTickCount)
          const intVal = Math.round(val)
          let valText = intVal.toString()
          if (valText.length > 6) valText = intVal.toLocaleString()
          const textWidth = ctx.measureText(valText).width
          ctx.fillText(valText, gridLeft - 10 - textWidth, y + 5)
        }
  
        // X轴标签(防拥挤)
        ctx.setFillStyle(xAxis.axisLabel?.color || '#666')
        ctx.setFontSize(xAxis.axisLabel?.fontSize || 12)
        const minLabelWidth = 30
        const maxShowLabels = Math.floor(drawWidth / minLabelWidth)
        const labelInterval = maxShowLabels < this.categories.length
            ? Math.ceil(this.categories.length / maxShowLabels)
            : 1
  
        this.categories.forEach((text, index) => {
          if (index % labelInterval === 0) {
            const x = gridLeft + index * xStep + xStep / 2
            let labelText = text
            if (text.length > 6) labelText = text.slice(0, 6) + '...'
            ctx.fillText(labelText, x - ctx.measureText(labelText).width / 2, height - gridBottom + 20)
          }
        })
  
cf70629b   刘淇   养护计划 照片 自己写样式
311
        // 绘制K线(K线本身就是直线,无平滑逻辑)
4f475013   刘淇   k线图
312
313
314
315
316
317
318
319
        this.data.forEach((item, index) => {
          const { open, high, low, close } = item
          const x = gridLeft + index * xStep + xStep / 2
          const yOpen = gridTop + drawHeight - ((open - minVal) / valRange) * drawHeight
          const yClose = gridTop + drawHeight - ((close - minVal) / valRange) * drawHeight
          const yHigh = gridTop + drawHeight - ((high - minVal) / valRange) * drawHeight
          const yLow = gridTop + drawHeight - ((low - minVal) / valRange) * drawHeight
  
cf70629b   刘淇   养护计划 照片 自己写样式
320
          // 绘制高低线(直线)
4f475013   刘淇   k线图
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
          ctx.setStrokeStyle(close >= open ? color[0] : color[1])
          ctx.setLineWidth(1)
          ctx.beginPath()
          ctx.moveTo(x, yHigh)
          ctx.lineTo(x, yLow)
          ctx.stroke()
  
          // 绘制实体
          const rectWidth = xStep / 3
          ctx.setFillStyle(close >= open ? color[0] : color[1])
          const rectY = Math.min(yOpen, yClose)
          const rectHeight = Math.abs(yClose - yOpen) || 2
          ctx.fillRect(x - rectWidth / 2, rectY, rectWidth, rectHeight)
        })
  
        ctx.draw()
      },
      touchStart (e) {
        this.touchInfo = {
          x: e.changedTouches[0].x,
          y: e.changedTouches[0].y,
          time: Date.now()
        }
      },
      touchMove (e) {
        this.touchInfo.x = e.changedTouches[0].x
        this.touchInfo.y = e.changedTouches[0].y
      },
      touchEnd (e) {
        // 可扩展点击交互逻辑
      }
    }
  }
  </script>
  
  <style scoped>
  .uni-charts {
    position: relative;
  }
  .charts-canvas {
    display: block;
  }
  .map-container {
    position: relative;
  }
  </style>