l-echart.vue 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  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. console.log(config,'config');
  321. // #ifndef APP-NVUE
  322. setCanvasCreator(echarts, config)
  323. try {
  324. console.log(typeof callback,'callback');
  325. this.chart = echarts.init(config.canvas, theme, Object.assign({}, config, opts))
  326. if(typeof callback === 'function') {
  327. callback(this.chart)
  328. } else {
  329. return this.chart
  330. }
  331. } catch(e) {
  332. console.error(e,'e')
  333. return null
  334. }
  335. // #endif
  336. // #ifdef APP-NVUE
  337. this.chart = new Echarts(this.$refs.webview)
  338. this.$refs.webview.evalJs(`init(null, null, ${JSON.stringify(opts)}, ${theme})`)
  339. if(callback) {
  340. callback(this.chart)
  341. } else {
  342. return this.chart
  343. }
  344. // #endif
  345. },
  346. getContext() {
  347. // #ifdef APP-NVUE
  348. if(this.finished) {
  349. return Promise.resolve(this.finished)
  350. }
  351. return new Promise(resolve => {
  352. this.$watch('finished', (val) => {
  353. if(val) {
  354. resolve(this.finished)
  355. }
  356. })
  357. })
  358. // #endif
  359. // #ifndef APP-NVUE
  360. return getRect(`#${this.canvasId}`, {context: this, type: this.use2dCanvas ? 'fields': 'boundingClientRect'}).then(res => {
  361. if(res) {
  362. let dpr = devicePixelRatio
  363. let {width, height, node} = res
  364. let canvas;
  365. this.width = width = width || 300;
  366. this.height = height = height || 300;
  367. if(node) {
  368. const ctx = node.getContext('2d');
  369. canvas = new Canvas(ctx, this, true, node);
  370. this.canvasNode = node
  371. } else {
  372. // #ifdef MP-TOUTIAO
  373. dpr = !this.isPC ? devicePixelRatio : 1// 1.25
  374. // #endif
  375. // #ifndef MP-ALIPAY || MP-TOUTIAO
  376. dpr = this.isPC ? devicePixelRatio : 1
  377. // #endif
  378. // #ifdef MP-ALIPAY || MP-LARK
  379. dpr = devicePixelRatio
  380. // #endif
  381. // #ifdef WEB
  382. dpr = 1
  383. // #endif
  384. this.rect = res
  385. this.nodeWidth = width * dpr;
  386. this.nodeHeight = height * dpr;
  387. const ctx = uni.createCanvasContext(this.canvasId, this);
  388. canvas = new Canvas(ctx, this, false);
  389. }
  390. return { canvas, width, height, devicePixelRatio: dpr, node };
  391. } else {
  392. return {}
  393. }
  394. })
  395. // #endif
  396. },
  397. // #ifndef APP-NVUE
  398. getRelative(e, touches) {
  399. let { clientX, clientY } = e
  400. if(!(clientX && clientY) && touches && touches[0]) {
  401. clientX = touches[0].clientX
  402. clientY = touches[0].clientY
  403. }
  404. return {x: clientX - this.rect.left, y: clientY - this.rect.top, wheelDelta: e.wheelDelta || 0}
  405. },
  406. getTouch(e, touches) {
  407. const {x} = touches && touches[0] || {}
  408. return x ? touches[0] : this.getRelative(e, touches);
  409. },
  410. touchStart(e) {
  411. this.isDown = true
  412. const next = () => {
  413. const touches = convertTouchesToArray(e.touches)
  414. if(this.chart) {
  415. const touch = this.getTouch(e, touches)
  416. this.startX = touch.x
  417. this.startY = touch.y
  418. this.startT = new Date()
  419. const handler = this.chart.getZr().handler;
  420. dispatch.call(handler, 'mousedown', touch)
  421. dispatch.call(handler, 'mousemove', touch)
  422. handler.processGesture(wrapTouch(e), 'start');
  423. clearTimeout(this.endTimer);
  424. }
  425. }
  426. if(this.isPC) {
  427. getRect(`#${this.canvasId}`, {context: this}).then(res => {
  428. this.rect = res
  429. next()
  430. })
  431. return
  432. }
  433. next()
  434. },
  435. touchMove(e) {
  436. if(this.isPC && this.enableHover && !this.isDown) {this.isDown = true}
  437. const touches = convertTouchesToArray(e.touches)
  438. if (this.chart && this.isDown) {
  439. const handler = this.chart.getZr().handler;
  440. dispatch.call(handler, 'mousemove', this.getTouch(e, touches))
  441. handler.processGesture(wrapTouch(e), 'change');
  442. }
  443. },
  444. touchEnd(e) {
  445. this.isDown = false
  446. if (this.chart) {
  447. const touches = convertTouchesToArray(e.changedTouches)
  448. const {x} = touches && touches[0] || {}
  449. const touch = (x ? touches[0] : this.getRelative(e, touches)) || {};
  450. const handler = this.chart.getZr().handler;
  451. const isClick = Math.abs(touch.x - this.startX) < 10 && new Date() - this.startT < 200;
  452. dispatch.call(handler, 'mouseup', touch)
  453. handler.processGesture(wrapTouch(e), 'end');
  454. if(isClick) {
  455. dispatch.call(handler, 'click', touch)
  456. } else {
  457. this.endTimer = setTimeout(() => {
  458. dispatch.call(handler, 'mousemove', {x: 999999999,y: 999999999});
  459. dispatch.call(handler, 'mouseup', {x: 999999999,y: 999999999});
  460. },50)
  461. }
  462. }
  463. },
  464. // #endif
  465. // #ifdef H5
  466. mousewheel(e){
  467. if(this.chart) {
  468. dispatch.call(this.chart.getZr().handler, 'mousewheel', this.getTouch(e))
  469. }
  470. }
  471. // #endif
  472. }
  473. };
  474. </script>
  475. <style>
  476. .lime-echart {
  477. position: relative;
  478. /* #ifndef APP-NVUE */
  479. width: 100%;
  480. height: 100%;
  481. /* #endif */
  482. /* #ifdef APP-NVUE */
  483. flex: 1;
  484. /* #endif */
  485. }
  486. .lime-echart__canvas {
  487. /* #ifndef APP-NVUE */
  488. width: 100%;
  489. height: 100%;
  490. /* #endif */
  491. /* #ifdef APP-NVUE */
  492. flex: 1;
  493. /* #endif */
  494. }
  495. /* #ifndef APP-NVUE */
  496. .lime-echart__mask {
  497. position: absolute;
  498. width: 100%;
  499. height: 100%;
  500. left: 0;
  501. top: 0;
  502. z-index: 1;
  503. }
  504. /* #endif */
  505. </style>