l-echart.vue 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. <template>
  2. <view class="lime-echart" :style="customStyle" v-if="canvasId" ref="limeEchart" :aria-label="ariaLabel">
  3. <!-- #ifndef APP-NVUE -->
  4. <canvas
  5. class="lime-echart__canvas"
  6. v-if="use2dCanvas"
  7. type="2d"
  8. :id="canvasId"
  9. :style="canvasStyle"
  10. :disable-scroll="isDisableScroll"
  11. @touchstart="touchStart"
  12. @touchmove="touchMove"
  13. @touchend="touchEnd"
  14. />
  15. <canvas
  16. class="lime-echart__canvas"
  17. v-else
  18. :width="nodeWidth"
  19. :height="nodeHeight"
  20. :style="canvasStyle"
  21. :canvas-id="canvasId"
  22. :id="canvasId"
  23. :disable-scroll="isDisableScroll"
  24. @touchstart="touchStart"
  25. @touchmove="touchMove"
  26. @touchend="touchEnd"
  27. />
  28. <view class="lime-echart__mask"
  29. v-if="isPC"
  30. @mousedown="touchStart"
  31. @mousemove="touchMove"
  32. @mouseup="touchEnd"
  33. @touchstart="touchStart"
  34. @touchmove="touchMove"
  35. @touchend="touchEnd">
  36. </view>
  37. <canvas v-if="isOffscreenCanvas" :style="offscreenStyle" :canvas-id="offscreenCanvasId"></canvas>
  38. <!-- #endif -->
  39. <!-- #ifdef APP-NVUE -->
  40. <web-view
  41. class="lime-echart__canvas"
  42. :id="canvasId"
  43. :style="canvasStyle"
  44. :webview-styles="webviewStyles"
  45. ref="webview"
  46. src="/uni_modules/lime-echart/static/uvue.html?v=1"
  47. @pagefinish="finished = true"
  48. @onPostMessage="onMessage"
  49. ></web-view>
  50. <!-- #endif -->
  51. </view>
  52. </template>
  53. <script>
  54. // #ifndef APP-NVUE
  55. import {Canvas, setCanvasCreator, dispatch} from './canvas';
  56. import {wrapTouch, convertTouchesToArray, devicePixelRatio ,sleep, canIUseCanvas2d, getRect} from './utils';
  57. // #endif
  58. // #ifdef APP-NVUE
  59. import { base64ToPath, sleep } from './utils';
  60. import {Echarts} from './nvue'
  61. // #endif
  62. const charts = {}
  63. const echartsObj = {}
  64. /**
  65. * LimeChart 图表
  66. * @description 全端兼容的eCharts
  67. * @tutorial https://ext.dcloud.net.cn/plugin?id=4899
  68. * @property {String} customStyle 自定义样式
  69. * @property {String} type 指定 canvas 类型
  70. * @value 2d 使用canvas 2d,部分小程序支持
  71. * @value '' 使用原生canvas,会有层级问题
  72. * @value bottom right 不缩放图片,只显示图片的右下边区域
  73. * @property {Boolean} isDisableScroll
  74. * @property {number} beforeDelay = [30] 延迟初始化 (毫秒)
  75. * @property {Boolean} enableHover PC端使用鼠标悬浮
  76. * @event {Function} finished 加载完成触发
  77. */
  78. export default {
  79. name: 'lime-echart',
  80. props: {
  81. // #ifdef MP-WEIXIN || MP-TOUTIAO
  82. type: {
  83. type: String,
  84. default: '2d'
  85. },
  86. // #endif
  87. // #ifdef APP-NVUE
  88. webviewStyles: Object,
  89. // hybrid: Boolean,
  90. // #endif
  91. customStyle: String,
  92. isDisableScroll: Boolean,
  93. isClickable: {
  94. type: Boolean,
  95. default: true
  96. },
  97. enableHover: Boolean,
  98. beforeDelay: {
  99. type: Number,
  100. default: 30
  101. }
  102. },
  103. data() {
  104. return {
  105. // #ifdef MP-WEIXIN || MP-TOUTIAO || MP-ALIPAY
  106. use2dCanvas: true,
  107. // #endif
  108. // #ifndef MP-WEIXIN || MP-TOUTIAO || MP-ALIPAY
  109. use2dCanvas: false,
  110. // #endif
  111. ariaLabel: '图表',
  112. width: null,
  113. height: null,
  114. nodeWidth: null,
  115. nodeHeight: null,
  116. // canvasNode: null,
  117. config: {},
  118. inited: false,
  119. finished: false,
  120. file: '',
  121. platform: '',
  122. isPC: false,
  123. isDown: false,
  124. isOffscreenCanvas: false,
  125. offscreenWidth: 0,
  126. offscreenHeight: 0
  127. };
  128. },
  129. computed: {
  130. canvasId() {
  131. return `lime-echart${this._ && this._.uid || this._uid}`
  132. },
  133. offscreenCanvasId() {
  134. return `${this.canvasId}_offscreen`
  135. },
  136. offscreenStyle() {
  137. return `width:${this.offscreenWidth}px;height: ${this.offscreenHeight}px; position: fixed; left: 99999px; background: red`
  138. },
  139. canvasStyle() {
  140. return this.width && this.height ? ('width:' + this.width + 'px;height:' + this.height + 'px') : ''
  141. }
  142. },
  143. // #ifndef VUE3
  144. beforeDestroy() {
  145. this.clear()
  146. this.dispose()
  147. // #ifdef H5
  148. if(this.isPC) {
  149. document.removeEventListener('mousewheel', this.mousewheel)
  150. }
  151. // #endif
  152. },
  153. // #endif
  154. // #ifdef VUE3
  155. beforeUnmount() {
  156. this.clear()
  157. this.dispose()
  158. // #ifdef H5
  159. if(this.isPC) {
  160. document.removeEventListener('mousewheel', this.mousewheel)
  161. }
  162. // #endif
  163. },
  164. // #endif
  165. created() {
  166. // #ifdef H5
  167. if(!('ontouchstart' in window)) {
  168. this.isPC = true
  169. document.addEventListener('mousewheel', this.mousewheel)
  170. }
  171. // #endif
  172. // #ifdef MP-WEIXIN || MP-TOUTIAO || MP-ALIPAY
  173. const { platform } = uni.getSystemInfoSync();
  174. this.isPC = /windows/i.test(platform)
  175. // #endif
  176. this.use2dCanvas = this.type === '2d' && canIUseCanvas2d()
  177. },
  178. mounted() {
  179. this.$nextTick(() => {
  180. this.$emit('finished')
  181. })
  182. },
  183. methods: {
  184. // #ifdef APP-NVUE
  185. onMessage(e) {
  186. const detail = e?.detail?.data[0] || null;
  187. const data = detail?.data
  188. const key = detail?.event
  189. const options = data?.options
  190. const event = data?.event
  191. const file = detail?.file
  192. if (key == 'log' && data) {
  193. console.log(data)
  194. }
  195. if(event) {
  196. this.chart.dispatchAction(event.replace(/"/g,''), options)
  197. }
  198. if(file) {
  199. thie.file = file
  200. }
  201. },
  202. // #endif
  203. setChart(callback) {
  204. if(!this.chart) {
  205. console.warn(`组件还未初始化,请先使用 init`)
  206. return
  207. }
  208. if(typeof callback === 'function' && this.chart) {
  209. callback(this.chart);
  210. }
  211. // #ifdef APP-NVUE
  212. if(typeof callback === 'function') {
  213. this.$refs.webview.evalJs(`setChart(${JSON.stringify(callback.toString())}, ${JSON.stringify(this.chart.options)})`);
  214. }
  215. // #endif
  216. },
  217. setOption() {
  218. if (!this.chart || !this.chart.setOption) {
  219. console.warn(`组件还未初始化,请先使用 init`)
  220. return
  221. }
  222. this.chart.setOption(...arguments);
  223. },
  224. showLoading() {
  225. if(this.chart) {
  226. this.chart.showLoading(...arguments)
  227. }
  228. },
  229. hideLoading() {
  230. if(this.chart) {
  231. this.chart.hideLoading()
  232. }
  233. },
  234. clear() {
  235. if(this.chart) {
  236. this.chart.clear()
  237. }
  238. },
  239. dispose() {
  240. if(this.chart) {
  241. this.chart.dispose()
  242. }
  243. },
  244. resize(size) {
  245. if(size && size.width && size.height) {
  246. this.height = size.height
  247. this.width = size.width
  248. if(this.chart) {this.chart.resize(size)}
  249. } else {
  250. this.$nextTick(() => {
  251. uni.createSelectorQuery()
  252. .in(this)
  253. .select(`.lime-echart`)
  254. .boundingClientRect()
  255. .exec(res => {
  256. if (res) {
  257. let { width, height } = res[0];
  258. this.width = width = width || 300;
  259. this.height = height = height || 300;
  260. this.chart.resize({width, height})
  261. }
  262. });
  263. })
  264. }
  265. },
  266. canvasToTempFilePath(args = {}) {
  267. // #ifndef APP-NVUE
  268. const { use2dCanvas, canvasId } = this;
  269. return new Promise((resolve, reject) => {
  270. const copyArgs = Object.assign({
  271. canvasId,
  272. success: resolve,
  273. fail: reject
  274. }, args);
  275. if (use2dCanvas) {
  276. delete copyArgs.canvasId;
  277. copyArgs.canvas = this.canvasNode;
  278. }
  279. uni.canvasToTempFilePath(copyArgs, this);
  280. });
  281. // #endif
  282. // #ifdef APP-NVUE
  283. this.file = ''
  284. this.$refs.webview.evalJs(`canvasToTempFilePath()`);
  285. return new Promise((resolve, reject) => {
  286. this.$watch('file', async (file) => {
  287. if(file) {
  288. const tempFilePath = await base64ToPath(file)
  289. resolve(args.success({tempFilePath}))
  290. } else {
  291. reject(args.fail({error: ``}))
  292. }
  293. })
  294. })
  295. // #endif
  296. },
  297. async init(echarts, ...args) {
  298. // #ifndef APP-NVUE
  299. if(args && args.length == 0 && !echarts) {
  300. console.error('缺少参数:init(echarts, theme?:string, opts?: object, callback?: function)')
  301. return
  302. }
  303. // #endif
  304. let theme=null,opts={},callback;
  305. Array.from(arguments).forEach(item => {
  306. if(typeof item === 'function') {
  307. callback = item
  308. }
  309. if(['string'].includes(typeof item)) {
  310. theme = item
  311. }
  312. if(typeof item === 'object') {
  313. opts = item
  314. }
  315. })
  316. if(this.beforeDelay) {
  317. await sleep(this.beforeDelay)
  318. }
  319. let config = await this.getContext();
  320. // #ifndef APP-NVUE
  321. setCanvasCreator(echarts, config)
  322. try {
  323. this.chart = echarts.init(config.canvas, theme, Object.assign({}, config, opts))
  324. if(typeof callback === 'function') {
  325. callback(this.chart)
  326. } else {
  327. return this.chart
  328. }
  329. } catch(e) {
  330. console.error(e,'e')
  331. return null
  332. }
  333. // #endif
  334. // #ifdef APP-NVUE
  335. this.chart = new Echarts(this.$refs.webview)
  336. this.$refs.webview.evalJs(`init(null, null, ${JSON.stringify(opts)}, ${theme})`)
  337. if(callback) {
  338. callback(this.chart)
  339. } else {
  340. return this.chart
  341. }
  342. // #endif
  343. },
  344. getContext() {
  345. // #ifdef APP-NVUE
  346. if(this.finished) {
  347. return Promise.resolve(this.finished)
  348. }
  349. return new Promise(resolve => {
  350. this.$watch('finished', (val) => {
  351. if(val) {
  352. resolve(this.finished)
  353. }
  354. })
  355. })
  356. // #endif
  357. // #ifndef APP-NVUE
  358. return getRect(`#${this.canvasId}`, {context: this, type: this.use2dCanvas ? 'fields': 'boundingClientRect'}).then(res => {
  359. if(res) {
  360. let dpr = devicePixelRatio
  361. let {width, height, node} = res
  362. let canvas;
  363. this.width = width = width || 300;
  364. this.height = height = height || 300;
  365. if(node) {
  366. const ctx = node.getContext('2d');
  367. canvas = new Canvas(ctx, this, true, node);
  368. this.canvasNode = node
  369. } else {
  370. // #ifdef MP-TOUTIAO
  371. dpr = !this.isPC ? devicePixelRatio : 1// 1.25
  372. // #endif
  373. // #ifndef MP-ALIPAY || MP-TOUTIAO
  374. dpr = this.isPC ? devicePixelRatio : 1
  375. // #endif
  376. // #ifdef MP-ALIPAY || MP-LARK
  377. dpr = devicePixelRatio
  378. // #endif
  379. // #ifdef WEB
  380. dpr = 1
  381. // #endif
  382. this.rect = res
  383. this.nodeWidth = width * dpr;
  384. this.nodeHeight = height * dpr;
  385. const ctx = uni.createCanvasContext(this.canvasId, this);
  386. canvas = new Canvas(ctx, this, false);
  387. }
  388. return { canvas, width, height, devicePixelRatio: dpr, node };
  389. } else {
  390. return {}
  391. }
  392. })
  393. // #endif
  394. },
  395. // #ifndef APP-NVUE
  396. getRelative(e, touches) {
  397. let { clientX, clientY } = e
  398. if(!(clientX && clientY) && touches && touches[0]) {
  399. clientX = touches[0].clientX
  400. clientY = touches[0].clientY
  401. }
  402. return {x: clientX - this.rect.left, y: clientY - this.rect.top, wheelDelta: e.wheelDelta || 0}
  403. },
  404. getTouch(e, touches) {
  405. const {x} = touches && touches[0] || {}
  406. return x ? touches[0] : this.getRelative(e, touches);
  407. },
  408. touchStart(e) {
  409. this.isDown = true
  410. const next = () => {
  411. const touches = convertTouchesToArray(e.touches)
  412. if(this.chart) {
  413. const touch = this.getTouch(e, touches)
  414. this.startX = touch.x
  415. this.startY = touch.y
  416. this.startT = new Date()
  417. const handler = this.chart.getZr().handler;
  418. dispatch.call(handler, 'mousedown', touch)
  419. dispatch.call(handler, 'mousemove', touch)
  420. handler.processGesture(wrapTouch(e), 'start');
  421. clearTimeout(this.endTimer);
  422. }
  423. }
  424. if(this.isPC) {
  425. getRect(`#${this.canvasId}`, {context: this}).then(res => {
  426. this.rect = res
  427. next()
  428. })
  429. return
  430. }
  431. next()
  432. },
  433. touchMove(e) {
  434. if(this.isPC && this.enableHover && !this.isDown) {this.isDown = true}
  435. const touches = convertTouchesToArray(e.touches)
  436. if (this.chart && this.isDown) {
  437. const handler = this.chart.getZr().handler;
  438. dispatch.call(handler, 'mousemove', this.getTouch(e, touches))
  439. handler.processGesture(wrapTouch(e), 'change');
  440. }
  441. },
  442. touchEnd(e) {
  443. this.isDown = false
  444. if (this.chart) {
  445. const touches = convertTouchesToArray(e.changedTouches)
  446. const {x} = touches && touches[0] || {}
  447. const touch = (x ? touches[0] : this.getRelative(e, touches)) || {};
  448. const handler = this.chart.getZr().handler;
  449. const isClick = Math.abs(touch.x - this.startX) < 10 && new Date() - this.startT < 200;
  450. dispatch.call(handler, 'mouseup', touch)
  451. handler.processGesture(wrapTouch(e), 'end');
  452. if(isClick) {
  453. dispatch.call(handler, 'click', touch)
  454. } else {
  455. this.endTimer = setTimeout(() => {
  456. dispatch.call(handler, 'mousemove', {x: 999999999,y: 999999999});
  457. dispatch.call(handler, 'mouseup', {x: 999999999,y: 999999999});
  458. },50)
  459. }
  460. }
  461. },
  462. // #endif
  463. // #ifdef H5
  464. mousewheel(e){
  465. if(this.chart) {
  466. dispatch.call(this.chart.getZr().handler, 'mousewheel', this.getTouch(e))
  467. }
  468. }
  469. // #endif
  470. }
  471. };
  472. </script>
  473. <style>
  474. .lime-echart {
  475. position: relative;
  476. /* #ifndef APP-NVUE */
  477. width: 100%;
  478. height: 100%;
  479. /* #endif */
  480. /* #ifdef APP-NVUE */
  481. flex: 1;
  482. /* #endif */
  483. }
  484. .lime-echart__canvas {
  485. /* #ifndef APP-NVUE */
  486. width: 100%;
  487. height: 100%;
  488. /* #endif */
  489. /* #ifdef APP-NVUE */
  490. flex: 1;
  491. /* #endif */
  492. }
  493. /* #ifndef APP-NVUE */
  494. .lime-echart__mask {
  495. position: absolute;
  496. width: 100%;
  497. height: 100%;
  498. left: 0;
  499. top: 0;
  500. z-index: 1;
  501. }
  502. /* #endif */
  503. </style>