This commit is contained in:
Sliverber 2024-01-24 11:55:35 +08:00
parent 8be15e8022
commit 6aa3876189
43 changed files with 3244 additions and 626 deletions

View File

@ -16,7 +16,4 @@ image {
width: 100%;
height: 100%;
}
@font-face {
font-family: 'YOUSHEBIAOTIHEI-2';
src: url('https://file.langsi.online/ttf/YOUSHEBIAOTIHEI-2.TTF')
}

View File

@ -0,0 +1,169 @@
## 0.8.12023-08-24
- fix: app 的`touch`事件为`object` 导致无法显示 `tooltip`
## 0.8.02023-08-22
- fix: 离屏 报错问题
- fix: 微信小程序PC无法使用事件
- chore: 更新文档
## 0.7.92023-07-29
- chore: 更新文档
## 0.7.82023-07-29
- fix: 离屏 报错问题
## 0.7.72023-07-27
- chore: 更新文档
- chore: lime-echart 里的示例使用自定tooltips
- feat: 对支持离屏的使用离屏创建(微信、字节、支付宝)
## 0.7.62023-06-30
- fix: vue3 报`width`的错
## 0.7.52023-05-25
- chore: 更新文档 和 demo, 使用`lime-echart`这个标签即可查看示例
## 0.7.42023-05-22
- chore: 增加关于钉钉小程序上传时提示安全问题的说明及修改建议
## 0.7.32023-05-16
- chore: 更新 vue3 非微信小程序平台可能缺少`wx`的说明
## 0.7.22023-05-16
- chore: 更新 vue3 非微信小程序平台的可以缺少`wx`的说明
## 0.7.12023-04-26
- chore: 更新demo使用`lime-echart`这个标签即可查看示例
- chore微信小程序的`tooltip`文字有阴影,怀疑是微信的锅,临时解决方法是`tooltip.shadowBlur = 0`
## 0.7.02023-04-24
- fix: 修复`setAttribute is not a function`
## 0.6.92023-04-15
- chore: 更新文档vue3请使用echarts esm的包
## 0.6.82023-03-22
- feat: mac pc无法使用canvas 2d
## 0.6.72023-03-17
- feat: 更新文档
## 0.6.62023-03-17
- feat: 微信小程序PC已经支持canvas 2d故去掉判断PC
## 0.6.52022-11-03
- fix: 某些手机touches为对象导致无法交互。
## 0.6.42022-10-28
- fix: 优化点击事件的触发条件
## 0.6.32022-10-26
- fix: 修复 dataZoom 拖动问题
## 0.6.22022-10-23
- fix: 修复 飞书小程序 尺寸问题
## 0.6.12022-10-19
- fix: 修复 PC mousewheel 事件 鼠标位置不准确的BUG不兼容火狐
- feat: showLoading 增加传参
## 0.6.02022-09-16
- feat: 增加PC的mousewheel事件
## 0.5.42022-09-16
- fix: 修复 nvue 动态数据不显示问题
## 0.5.32022-09-16
- feat: 增加enableHover属性 在PC端时当鼠标进入显示tooltip不必按下。
- chore: 更新文档
## 0.5.22022-09-16
- feat: 增加enableHover属性 在PC端时当鼠标进入显示tooltip不必按下。
## 0.5.12022-09-16
- fix: 修复nvue报错
## 0.5.02022-09-15
- feat: init(echarts, theme?:string, opts?:{}, callback: function(chart))
## 0.4.82022-09-11
- feat: 增加 @finished
## 0.4.72022-08-24
- chore: 去掉 stylus
## 0.4.62022-08-24
- feat: 增加 beforeDelay
## 0.4.52022-08-12
- chore: 更新文档
## 0.4.42022-08-12
- fix: 修复 resize 无参数时报错
## 0.4.32022-08-07
# 评论有说本插件对新手不友好,让我做不好就不要发出来。 还有的说跟官网一样,发出来做什么,给我整无语了。
# 所以在此提醒一下准备要下载的你,如果你从未使用过 echarts 请不要下载 或 谨慎下载。
# 如果你确认要下载麻烦看完文档。还有请注意插件是让echarts在uniapp能运行API 配置请自行去官网查阅!
# 如果你不会echarts 但又需要图表,市场上有个很优秀的图表插件 uchart 你可以去使用这款插件uchart的作者人很好也热情。
# 每个人都有自己的本职工作,如果你能力强可以自行兼容,如果使用了他人的插件也麻烦尊重他人的成果和劳动时间。谢谢。
# 为了心情愉悦,本人已经使用插件屏蔽差评。
- chore: 更新文档
## 0.4.22022-07-20
- feat: 增加 resize
## 0.4.12022-06-07
- fix: 修复 canvasToTempFilePath 不生效问题
## 0.4.02022-06-04
- chore 为了词云 增加一个canvas 标签
- 词云下载地址[echart-wordcloud](https://ext.dcloud.net.cn/plugin?id=8430)
## 0.3.92022-06-02
- chore: 更新文档
- tips: lines 不支持 `trailLength`
## 0.3.82022-05-31
- fix: 修复 因mouse事件冲突tooltip跳动问题
## 0.3.72022-05-26
- chore: 更新文档
- chore: 设置默认宽高300px
- fix: 修复 vue3 微信小程序 拖影BUG
- chore: 支持PC
## 0.3.52022-04-28
- chore: 更新使用方式
- 🔔 必须使用hbuilderx 3.4.8-alpha以上
## 0.3.42021-08-03
- chore: 增加 setOption的参数值
## 0.3.32021-07-22
- fix: 修复 径向渐变报错的问题
## 0.3.22021-07-09
- chore: 统一命名规范,无须主动引入组件
## [代码示例站点1](https://limeui.qcoon.cn/#/echart-example)
## [代码示例站点2](http://liangei.gitee.io/limeui/#/echart-example)
## 0.3.12021-06-21
- fix: 修复 app-nvue ios is-enable 无效的问题
## [代码示例站点1](https://limeui.qcoon.cn/#/echart-example)
## [代码示例站点2](http://liangei.gitee.io/limeui/#/echart-example)
## 0.3.02021-06-14
- fix: 修复 头条系小程序 2d 报 JSON.stringify 的问题
- 目前 头条系小程序 2d 无法在开发工具上预览划动图表页面无法滚动axisLabel 字体颜色无法更改建议使用非2d。
## 0.2.92021-06-06
- fix: 修复 头条系小程序 2d 放大的BUG
- 头条系小程序 2d 无法在开发工具上预览,也存在划动图表页面无法滚动的问题。
## [代码示例http://liangei.gitee.io/limeui/#/echart-example](http://liangei.gitee.io/limeui/#/echart-example)
## 0.2.82021-05-19
- fix: 修复 微信小程序 PC 显示过大的问题
## 0.2.72021-05-19
- fix: 修复 微信小程序 PC 不显示问题
## [代码示例http://liangei.gitee.io/limeui/#/echart-example](http://liangei.gitee.io/limeui/#/echart-example)
## 0.2.62021-05-14
- feat: 支持 `image`
- feat: props 增加 `ec.clear`,更新时是否先删除图表样式
- feat: props 增加 `isDisableScroll` ,触摸图表时是否禁止页面滚动
- feat: props 增加 `webviewStyles` webview 的样式, 仅nvue有效
## 0.2.52021-05-13
- docs: 插件用到了css 预编译器 [stylus](https://ext.dcloud.net.cn/plugin?name=compile-stylus) 请安装它
## 0.2.42021-05-12
- fix: 修复 百度平台 多个图表ctx 和 渐变色 bug
- ## [代码示例http://liangei.gitee.io/limeui/#/echart-example](http://liangei.gitee.io/limeui/#/echart-example)
## 0.2.32021-05-10
- feat: 增加 `canvasToTempFilePath` 方法,用于生成图片
```js
this.$refs.chart.canvasToTempFilePath({success: (res) => {
console.log('tempFilePath:', res.tempFilePath)
}})
```
## 0.2.22021-05-10
- feat: 增加 `dispose` 方法,用于销毁实例
- feat: 增加 `isClickable` 是否派发点击
- feat: 实验性的支持 `nvue` 使用要慎重考虑
- ## [代码示例http://liangei.gitee.io/limeui/#/echart-example](http://liangei.gitee.io/limeui/#/echart-example)
## 0.2.12021-05-06
- fix修复 微信小程序 json 报错
- chore: `reset` 更改为 `setChart`
- feat: 增加 `isEnable` 开启初始化 启用这个后 无须再使用`init`方法
```html
<l-echart ref="chart" is-enable />
```
```js
// 显示加载
this.$refs.chart.showLoading()
// 使用实例回调
this.$refs.chart.setChart(chart => ...code)
// 直接设置图表配置
this.$refs.chart.setOption(data)
```
## 0.2.02021-05-05
- fix修复 头条 百度 偏移的问题
- docs: 更新文档
## [代码示例http://liangei.gitee.io/limeui/#/echart-example](http://liangei.gitee.io/limeui/#/echart-example)
## 0.1.02021-05-02
- chore: 第一次上传,基本全端兼容,使用方法与官网一致。
- 已知BUG非2d 无法使用背景色,已反馈官方
- 已知BUG头条 百度 有许些偏移
- 后期计划兼容nvue

View File

@ -0,0 +1,385 @@
const cacheChart = {}
const fontSizeReg = /([\d\.]+)px/;
class EventEmit {
constructor() {
this.__events = {};
}
on(type, listener) {
if (!type || !listener) {
return;
}
const events = this.__events[type] || [];
events.push(listener);
this.__events[type] = events;
}
emit(type, e) {
if (type.constructor === Object) {
e = type;
type = e && e.type;
}
if (!type) {
return;
}
const events = this.__events[type];
if (!events || !events.length) {
return;
}
events.forEach((listener) => {
listener.call(this, e);
});
}
off(type, listener) {
const __events = this.__events;
const events = __events[type];
if (!events || !events.length) {
return;
}
if (!listener) {
delete __events[type];
return;
}
for (let i = 0, len = events.length; i < len; i++) {
if (events[i] === listener) {
events.splice(i, 1);
i--;
}
}
}
}
class Image {
constructor() {
this.currentSrc = null
this.naturalHeight = 0
this.naturalWidth = 0
this.width = 0
this.height = 0
this.tagName = 'IMG'
}
set src(src) {
this.currentSrc = src
uni.getImageInfo({
src,
success: (res) => {
this.naturalWidth = this.width = res.width
this.naturalHeight = this.height = res.height
this.onload()
},
fail: () => {
this.onerror()
}
})
}
get src() {
return this.currentSrc
}
}
class OffscreenCanvas {
constructor(ctx, com, canvasId) {
this.tagName = 'canvas'
this.com = com
this.canvasId = canvasId
this.ctx = ctx
}
set width(w) {
this.com.offscreenWidth = w
}
set height(h) {
this.com.offscreenHeight = h
}
get width() {
return this.com.offscreenWidth || 0
}
get height() {
return this.com.offscreenHeight || 0
}
getContext(type) {
return this.ctx
}
getImageData() {
return new Promise((resolve, reject) => {
this.com.$nextTick(() => {
uni.canvasGetImageData({
x:0,
y:0,
width: this.com.offscreenWidth,
height: this.com.offscreenHeight,
canvasId: this.canvasId,
success: (res) => {
resolve(res)
},
fail: (err) => {
reject(err)
},
}, this.com)
})
})
}
}
export class Canvas {
constructor(ctx, com, isNew, canvasNode={}) {
cacheChart[com.canvasId] = {ctx}
this.canvasId = com.canvasId;
this.chart = null;
this.isNew = isNew
this.tagName = 'canvas'
this.canvasNode = canvasNode;
this.com = com;
if (!isNew) {
this._initStyle(ctx)
}
this._initEvent();
this._ee = new EventEmit()
}
getContext(type) {
if (type === '2d') {
return this.ctx;
}
}
setAttribute(key, value) {
if(key === 'aria-label') {
this.com['ariaLabel'] = value
}
}
setChart(chart) {
this.chart = chart;
}
createOffscreenCanvas(param){
if(!this.children) {
this.com.isOffscreenCanvas = true
this.com.offscreenWidth = param.width||300
this.com.offscreenHeight = param.height||300
const com = this.com
const canvasId = this.com.offscreenCanvasId
const context = uni.createCanvasContext(canvasId, this.com)
this._initStyle(context)
this.children = new OffscreenCanvas(context, com, canvasId)
}
return this.children
}
appendChild(child) {
console.log('child', child)
}
dispatchEvent(type, e) {
if(typeof type == 'object') {
this._ee.emit(type.type, type);
} else {
this._ee.emit(type, e);
}
return true
}
attachEvent() {
}
detachEvent() {
}
addEventListener(type, listener) {
this._ee.on(type, listener)
}
removeEventListener(type, listener) {
this._ee.off(type, listener)
}
_initCanvas(zrender, ctx) {
// zrender.util.getContext = function() {
// return ctx;
// };
// zrender.util.$override('measureText', function(text, font) {
// ctx.font = font || '12px sans-serif';
// return ctx.measureText(text, font);
// });
}
_initStyle(ctx, child) {
const styles = [
'fillStyle',
'strokeStyle',
'fontSize',
'globalAlpha',
'opacity',
'textAlign',
'textBaseline',
'shadow',
'lineWidth',
'lineCap',
'lineJoin',
'lineDash',
'miterLimit',
// 'font'
];
const colorReg = /#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])\b/g;
styles.forEach(style => {
Object.defineProperty(ctx, style, {
set: value => {
// if (style === 'font' && fontSizeReg.test(value)) {
// const match = fontSizeReg.exec(value);
// ctx.setFontSize(match[1]);
// return;
// }
if (style === 'opacity') {
ctx.setGlobalAlpha(value)
return;
}
if (style !== 'fillStyle' && style !== 'strokeStyle' || value !== 'none' && value !== null) {
// #ifdef H5 || APP-PLUS || MP-BAIDU
if(typeof value == 'object') {
if (value.hasOwnProperty('colorStop') || value.hasOwnProperty('colors')) {
ctx['set' + style.charAt(0).toUpperCase() + style.slice(1)](value);
}
return
}
// #endif
// #ifdef MP-TOUTIAO
if(colorReg.test(value)) {
value = value.replace(colorReg, '#$1$1$2$2$3$3')
}
// #endif
ctx['set' + style.charAt(0).toUpperCase() + style.slice(1)](value);
}
}
});
});
if(!this.isNew && !child) {
ctx.uniDrawImage = ctx.drawImage
ctx.drawImage = (...a) => {
a[0] = a[0].src
ctx.uniDrawImage(...a)
}
}
if(!ctx.createRadialGradient) {
ctx.createRadialGradient = function() {
return ctx.createCircularGradient(...[...arguments].slice(-3))
};
}
// 字节不支持
if (!ctx.strokeText) {
ctx.strokeText = (...a) => {
ctx.fillText(...a)
}
}
// 钉钉不支持
if (!ctx.measureText) {
const strLen = (str) => {
let len = 0;
for (let i = 0; i < str.length; i++) {
if (str.charCodeAt(i) > 0 && str.charCodeAt(i) < 128) {
len++;
} else {
len += 2;
}
}
return len;
}
ctx.measureText = (text, font) => {
let fontSize = ctx?.state?.fontSize || 12;
if (font) {
fontSize = parseInt(font.match(/([\d\.]+)px/)[1])
}
fontSize /= 2;
let isBold = fontSize >= 16;
const widthFactor = isBold ? 1.3 : 1;
return {
width: strLen(text) * fontSize * widthFactor
};
}
}
}
_initEvent(e) {
this.event = {};
const eventNames = [{
wxName: 'touchStart',
ecName: 'mousedown'
}, {
wxName: 'touchMove',
ecName: 'mousemove'
}, {
wxName: 'touchEnd',
ecName: 'mouseup'
}, {
wxName: 'touchEnd',
ecName: 'click'
}];
eventNames.forEach(name => {
this.event[name.wxName] = e => {
const touch = e.touches[0];
this.chart.getZr().handler.dispatch(name.ecName, {
zrX: name.wxName === 'tap' ? touch.clientX : touch.x,
zrY: name.wxName === 'tap' ? touch.clientY : touch.y
});
};
});
}
set width(w) {
this.canvasNode.width = w
}
set height(h) {
this.canvasNode.height = h
}
get width() {
return this.canvasNode.width || 0
}
get height() {
return this.canvasNode.height || 0
}
get ctx() {
return cacheChart[this.canvasId]['ctx'] || null
}
set chart(chart) {
cacheChart[this.canvasId]['chart'] = chart
}
get chart() {
return cacheChart[this.canvasId]['chart'] || null
}
}
export function dispatch(name, {x,y, wheelDelta}) {
this.dispatch(name, {
zrX: x,
zrY: y,
zrDelta: wheelDelta,
preventDefault: () => {},
stopPropagation: () =>{}
});
}
export function setCanvasCreator(echarts, {canvas, node}) {
// echarts.setCanvasCreator(() => canvas);
if(echarts && !echarts.registerPreprocessor) {
return console.warn('echarts 版本不对或未传入echartsvue3请使用esm格式')
}
echarts.registerPreprocessor(option => {
if (option && option.series) {
if (option.series.length > 0) {
option.series.forEach(series => {
series.progressive = 0;
});
} else if (typeof option.series === 'object') {
option.series.progressive = 0;
}
}
});
function loadImage(src, onload, onerror) {
let img = null
if(node && node.createImage) {
img = node.createImage()
img.onload = onload.bind(img);
img.onerror = onerror.bind(img);
img.src = src;
return img
} else {
img = new Image()
img.onload = onload.bind(img)
img.onerror = onerror.bind(img);
img.src = src
return img
}
}
if(echarts.setPlatformAPI) {
echarts.setPlatformAPI({
loadImage: canvas.setChart ? loadImage : null,
createCanvas(){
const key = 'createOffscreenCanvas'
return uni.canIUse(key) && uni[key] ? uni[key]({type: '2d'}) : canvas
}
})
}
}

View File

@ -0,0 +1,502 @@
<template>
<view class="lime-echart" :style="customStyle" v-if="canvasId" ref="limeEchart" :aria-label="ariaLabel">
<!-- #ifndef APP-NVUE -->
<canvas
class="lime-echart__canvas"
v-if="use2dCanvas"
type="2d"
:id="canvasId"
:style="canvasStyle"
:disable-scroll="isDisableScroll"
@touchstart="touchStart"
@touchmove="touchMove"
@touchend="touchEnd"
/>
<!-- <canvas
class="lime-echart__canvas"
v-else-if="isPC"
:style="canvasStyle"
:id="canvasId"
:canvas-id="canvasId"
:disable-scroll="isDisableScroll"
@mousedown="touchStart"
@mousemove="touchMove"
@mouseup="touchEnd"
/> -->
<canvas
class="lime-echart__canvas"
v-else
:width="nodeWidth"
:height="nodeHeight"
:style="canvasStyle"
:canvas-id="canvasId"
:id="canvasId"
:disable-scroll="isDisableScroll"
@touchstart="touchStart"
@touchmove="touchMove"
@touchend="touchEnd"
/>
<view class="lime-echart__mask"
v-if="isPC"
@mousedown="touchStart"
@mousemove="touchMove"
@mouseup="touchEnd"
@touchstart="touchStart"
@touchmove="touchMove"
@touchend="touchEnd">
</view>
<canvas v-if="isOffscreenCanvas" :style="offscreenStyle" :canvas-id="offscreenCanvasId"></canvas>
<!-- #endif -->
<!-- #ifdef APP-NVUE -->
<web-view
class="lime-echart__canvas"
:id="canvasId"
:style="canvasStyle"
:webview-styles="webviewStyles"
ref="webview"
src="/uni_modules/lime-echart/static/index.html"
@pagefinish="finished = true"
@onPostMessage="onMessage"
></web-view>
<!-- #endif -->
</view>
</template>
<script>
// #ifdef VUE3
// #ifdef APP-PLUS
global = {}
// #endif
// #endif
// #ifndef APP-NVUE
import {Canvas, setCanvasCreator, dispatch} from './canvas';
import {wrapTouch, convertTouchesToArray, devicePixelRatio ,sleep, canIUseCanvas2d, getRect} from './utils';
// #endif
// #ifdef APP-NVUE
import { base64ToPath, sleep } from './utils';
import {Echarts} from './nvue'
// #endif
const charts = {}
const echartsObj = {}
export default {
name: 'lime-echart',
props: {
// #ifdef MP-WEIXIN || MP-TOUTIAO
type: {
type: String,
default: '2d'
},
// #endif
// #ifdef APP-NVUE
webviewStyles: Object,
// hybrid: Boolean,
// #endif
customStyle: String,
isDisableScroll: Boolean,
isClickable: {
type: Boolean,
default: true
},
enableHover: Boolean,
beforeDelay: {
type: Number,
default: 30
}
},
data() {
return {
// #ifdef MP-WEIXIN || MP-TOUTIAO || MP-ALIPAY
use2dCanvas: true,
// #endif
// #ifndef MP-WEIXIN || MP-TOUTIAO || MP-ALIPAY
use2dCanvas: false,
// #endif
ariaLabel: '图表',
width: null,
height: null,
nodeWidth: null,
nodeHeight: null,
// canvasNode: null,
config: {},
inited: false,
finished: false,
file: '',
platform: '',
isPC: false,
isDown: false,
isOffscreenCanvas: false,
offscreenWidth: 0,
offscreenHeight: 0
};
},
computed: {
canvasId() {
return `lime-echart${this._ && this._.uid || this._uid}`
},
offscreenCanvasId() {
return `${this.canvasId}_offscreen`
},
offscreenStyle() {
return `width:${this.offscreenWidth}px;height: ${this.offscreenHeight}px; position: fixed; left: 99999px; background: red`
},
canvasStyle() {
return this.width && this.height ? ('width:' + this.width + 'px;height:' + this.height + 'px') : ''
}
},
// #ifndef VUE3
beforeDestroy() {
this.clear()
this.dispose()
// #ifdef H5
if(this.isPC) {
document.removeEventListener('mousewheel', this.mousewheel)
}
// #endif
},
// #endif
// #ifdef VUE3
unmounted() {
this.clear()
this.dispose()
// #ifdef H5
if(this.isPC) {
document.removeEventListener('mousewheel', this.mousewheel)
}
// #endif
},
// #endif
created() {
// #ifdef H5
if(!('ontouchstart' in window)) {
this.isPC = true
document.addEventListener('mousewheel', this.mousewheel)
}
// #endif
// #ifdef MP-WEIXIN || MP-TOUTIAO || MP-ALIPAY
const { platform } = uni.getSystemInfoSync();
this.isPC = /windows/i.test(platform)
// #endif
this.use2dCanvas = this.type === '2d' && canIUseCanvas2d()
},
mounted() {
this.$nextTick(() => {
this.$emit('finished')
})
},
methods: {
// #ifdef APP-NVUE
onMessage(e) {
const res = e?.detail?.data[0] || null;
if (res?.event) {
if(res.event === 'inited') {
this.inited = true
}
this.$emit(res.event, JSON.parse(res.data));
} else if(res?.file){
this.file = res.data
} else if(!res[0] && JSON.stringify(res[0]) != '{}'){
console.error(res);
} else {
console.log(...res)
}
},
// #endif
setChart(callback) {
if(!this.chart) {
console.warn(`组件还未初始化,请先使用 init`)
return
}
if(typeof callback === 'function' && this.chart) {
callback(this.chart);
}
// #ifdef APP-NVUE
if(typeof callback === 'function') {
this.$refs.webview.evalJs(`setChart(${JSON.stringify(callback.toString())}, ${JSON.stringify(this.chart.options)})`);
}
// #endif
},
setOption() {
if (!this.chart || !this.chart.setOption) {
console.warn(`组件还未初始化,请先使用 init`)
return
}
this.chart.setOption(...arguments);
},
showLoading() {
if(this.chart) {
this.chart.showLoading(...arguments)
}
},
hideLoading() {
if(this.chart) {
this.chart.hideLoading()
}
},
clear() {
if(this.chart) {
this.chart.clear()
}
},
dispose() {
if(this.chart) {
this.chart.dispose()
}
},
resize(size) {
if(size && size.width && size.height) {
this.height = size.height
this.width = size.width
if(this.chart) {this.chart.resize(size)}
} else {
this.$nextTick(() => {
uni.createSelectorQuery()
.in(this)
.select(`.lime-echart`)
.boundingClientRect()
.exec(res => {
if (res) {
let { width, height } = res[0];
this.width = width = width || 300;
this.height = height = height || 300;
this.chart.resize({width, height})
}
});
})
}
},
canvasToTempFilePath(args = {}) {
// #ifndef APP-NVUE
const { use2dCanvas, canvasId } = this;
return new Promise((resolve, reject) => {
const copyArgs = Object.assign({
canvasId,
success: resolve,
fail: reject
}, args);
if (use2dCanvas) {
delete copyArgs.canvasId;
copyArgs.canvas = this.canvasNode;
}
uni.canvasToTempFilePath(copyArgs, this);
});
// #endif
// #ifdef APP-NVUE
this.file = ''
this.$refs.webview.evalJs(`canvasToTempFilePath()`);
return new Promise((resolve, reject) => {
this.$watch('file', async (file) => {
if(file) {
const tempFilePath = await base64ToPath(file)
resolve(args.success({tempFilePath}))
} else {
reject(args.fail({error: ``}))
}
})
})
// #endif
},
async init(echarts, ...args) {
// #ifndef APP-NVUE
if(arguments && arguments.length < 1) {
console.error('缺少参数init(echarts, theme?:string, opts?: object, callback?: function)')
return
}
// #endif
let theme=null,opts={},callback;
Array.from(arguments).forEach(item => {
if(typeof item === 'function') {
callback = item
}
if(['string'].includes(typeof item)) {
theme = item
}
if(typeof item === 'object') {
opts = item
}
})
if(this.beforeDelay) {
await sleep(this.beforeDelay)
}
let config = await this.getContext();
// #ifndef APP-NVUE
setCanvasCreator(echarts, config)
this.chart = echarts.init(config.canvas, theme, Object.assign({}, config, opts))
if(typeof callback === 'function') {
callback(this.chart)
} else {
return this.chart
}
// #endif
// #ifdef APP-NVUE
this.chart = new Echarts(this.$refs.webview)
this.$refs.webview.evalJs(`init(null, null, ${JSON.stringify(opts)}, ${theme})`)
if(callback) {
callback(this.chart)
} else {
return this.chart
}
// #endif
},
getContext() {
// #ifdef APP-NVUE
if(this.finished) {
return Promise.resolve(this.finished)
}
return new Promise(resolve => {
this.$watch('finished', (val) => {
if(val) {
resolve(this.finished)
}
})
})
// #endif
// #ifndef APP-NVUE
return getRect(`#${this.canvasId}`, {context: this, type: this.use2dCanvas ? 'fields': 'boundingClientRect'}).then(res => {
if(res) {
let dpr = devicePixelRatio
let {width, height, node} = res
let canvas;
this.width = width = width || 300;
this.height = height = height || 300;
if(node) {
const ctx = node.getContext('2d');
canvas = new Canvas(ctx, this, true, node);
this.canvasNode = node
} else {
// #ifdef MP-TOUTIAO
dpr = !this.isPC ? devicePixelRatio : 1// 1.25
// #endif
// #ifndef MP-ALIPAY || MP-TOUTIAO
dpr = this.isPC ? devicePixelRatio : 1
// #endif
// #ifdef MP-ALIPAY || MP-LARK
dpr = devicePixelRatio
// #endif
this.rect = res
this.nodeWidth = width * dpr;
this.nodeHeight = height * dpr;
const ctx = uni.createCanvasContext(this.canvasId, this);
canvas = new Canvas(ctx, this, false);
}
return { canvas, width, height, devicePixelRatio: dpr, node };
} else {
return {}
}
})
// #endif
},
// #ifndef APP-NVUE
getRelative(e, touches) {
let { clientX, clientY } = e
if(!(clientX && clientY) && touches && touches[0]) {
clientX = touches[0].clientX
clientY = touches[0].clientY
}
return {x: clientX - this.rect.left, y: clientY - this.rect.top, wheelDelta: e.wheelDelta || 0}
},
getTouch(e, touches) {
const {x} = touches && touches[0] || {}
return x ? touches[0] : this.getRelative(e, touches);
},
touchStart(e) {
this.isDown = true
const next = () => {
const touches = convertTouchesToArray(e.touches)
if(this.chart) {
const touch = this.getTouch(e, touches)
this.startX = touch.x
this.startY = touch.y
this.startT = new Date()
const handler = this.chart.getZr().handler;
dispatch.call(handler, 'mousedown', touch)
dispatch.call(handler, 'mousemove', touch)
handler.processGesture(wrapTouch(e), 'start');
clearTimeout(this.endTimer);
}
}
if(this.isPC) {
getRect(`#${this.canvasId}`, {context: this}).then(res => {
this.rect = res
next()
})
return
}
next()
},
touchMove(e) {
if(this.isPC && this.enableHover && !this.isDown) {this.isDown = true}
const touches = convertTouchesToArray(e.touches)
if (this.chart && this.isDown) {
const handler = this.chart.getZr().handler;
dispatch.call(handler, 'mousemove', this.getTouch(e, touches))
handler.processGesture(wrapTouch(e), 'change');
}
},
touchEnd(e) {
this.isDown = false
if (this.chart) {
const touches = convertTouchesToArray(e.changedTouches)
const {x} = touches && touches[0] || {}
const touch = (x ? touches[0] : this.getRelative(e, touches)) || {};
const handler = this.chart.getZr().handler;
const isClick = Math.abs(touch.x - this.startX) < 10 && new Date() - this.startT < 200;
dispatch.call(handler, 'mouseup', touch)
handler.processGesture(wrapTouch(e), 'end');
if(isClick) {
dispatch.call(handler, 'click', touch)
} else {
this.endTimer = setTimeout(() => {
dispatch.call(handler, 'mousemove', {x: 999999999,y: 999999999});
dispatch.call(handler, 'mouseup', {x: 999999999,y: 999999999});
},50)
}
}
},
// #endif
// #ifdef H5
mousewheel(e){
if(this.chart) {
dispatch.call(this.chart.getZr().handler, 'mousewheel', this.getTouch(e))
}
}
// #endif
}
};
</script>
<style>
.lime-echart {
position: relative;
/* #ifndef APP-NVUE */
width: 100%;
height: 100%;
/* #endif */
/* #ifdef APP-NVUE */
flex: 1;
/* #endif */
}
.lime-echart__canvas {
/* #ifndef APP-NVUE */
width: 100%;
height: 100%;
/* #endif */
/* #ifdef APP-NVUE */
flex: 1;
/* #endif */
}
/* #ifndef APP-NVUE */
.lime-echart__mask {
position: absolute;
width: 100%;
height: 100%;
left: 0;
top: 0;
z-index: 1;
}
/* #endif */
</style>

View File

@ -0,0 +1,35 @@
export class Echarts {
constructor(webview) {
this.webview = webview
this.options = null
}
setOption() {
this.options = arguments
this.webview.evalJs(`setOption(${JSON.stringify(arguments)})`);
}
getOption() {
return this.options
}
showLoading() {
this.webview.evalJs(`showLoading(${JSON.stringify(arguments)})`);
}
hideLoading() {
this.webview.evalJs(`hideLoading()`);
}
clear() {
this.webview.evalJs(`clear()`);
}
dispose() {
this.webview.evalJs(`dispose()`);
}
resize(size) {
if(size) {
this.webview.evalJs(`resize(${size})`);
} else {
this.webview.evalJs(`resize()`);
}
}
on(type, ...args) {
console.warn('nvue 暂不支持事件')
}
}

View File

@ -0,0 +1,145 @@
// #ifndef APP-NVUE
// 计算版本
export function compareVersion(v1, v2) {
v1 = v1.split('.')
v2 = v2.split('.')
const len = Math.max(v1.length, v2.length)
while (v1.length < len) {
v1.push('0')
}
while (v2.length < len) {
v2.push('0')
}
for (let i = 0; i < len; i++) {
const num1 = parseInt(v1[i], 10)
const num2 = parseInt(v2[i], 10)
if (num1 > num2) {
return 1
} else if (num1 < num2) {
return -1
}
}
return 0
}
const systemInfo = uni.getSystemInfoSync();
function gte(version) {
// 截止 2023-03-22 mac pc小程序不支持 canvas 2d
let {
SDKVersion,
platform
} = systemInfo;
// #ifdef MP-ALIPAY
SDKVersion = my.SDKVersion
// #endif
// #ifdef MP-WEIXIN
return platform !== 'mac' && compareVersion(SDKVersion, version) >= 0;
// #endif
return compareVersion(SDKVersion, version) >= 0;
}
export function canIUseCanvas2d() {
// #ifdef MP-WEIXIN
return gte('2.9.0');
// #endif
// #ifdef MP-ALIPAY
return gte('2.7.0');
// #endif
// #ifdef MP-TOUTIAO
return gte('1.78.0');
// #endif
return false
}
export function convertTouchesToArray(touches) {
// 如果 touches 是一个数组,则直接返回它
if (Array.isArray(touches)) {
return touches;
}
// 如果touches是一个对象则转换为数组
if (typeof touches === 'object' && touches !== null) {
return Object.values(touches);
}
// 对于其他类型,直接返回它
return touches;
}
export function wrapTouch(event) {
for (let i = 0; i < event.touches.length; ++i) {
const touch = event.touches[i];
touch.offsetX = touch.x;
touch.offsetY = touch.y;
}
return event;
}
export const devicePixelRatio = uni.getSystemInfoSync().pixelRatio
// #endif
// #ifdef APP-NVUE
export function base64ToPath(base64) {
return new Promise((resolve, reject) => {
const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64) || [];
const bitmap = new plus.nativeObj.Bitmap('bitmap' + Date.now())
bitmap.loadBase64Data(base64, () => {
if (!format) {
reject(new Error('ERROR_BASE64SRC_PARSE'))
}
const time = new Date().getTime();
const filePath = `_doc/uniapp_temp/${time}.${format}`
bitmap.save(filePath, {},
() => {
bitmap.clear()
resolve(filePath)
},
(error) => {
bitmap.clear()
console.error(`${JSON.stringify(error)}`)
reject(error)
})
}, (error) => {
bitmap.clear()
console.error(`${JSON.stringify(error)}`)
reject(error)
})
})
}
// #endif
export function sleep(time) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(true)
}, time)
})
}
export function getRect(selector, options = {}) {
const typeDefault = 'boundingClientRect'
const {
context,
type = typeDefault
} = options
return new Promise((resolve, reject) => {
const dom = uni.createSelectorQuery().in(context).select(selector);
const result = (rect) => {
if (rect) {
resolve(rect)
} else {
reject()
}
}
if (type == typeDefault) {
dom[type](result).exec()
} else {
dom[type]({
node: true,
size: true,
rect: true
}, result).exec()
}
});
};

View File

@ -0,0 +1,149 @@
<template>
<view >
<view style="height: 750rpx; background-color: aquamarine; position: relative">
<l-echart ref="chart" @finished="init"></l-echart>
<view class="customTooltips" :style="{left: position[0] + 'px',top: position[1] + 'px'}" v-if="params.length && position.length && showTip">
<view>这是个自定的tooltips</view>
<view>{{params[0]['axisValue']}}</view>
<view v-for="item in params">
<view>
<text>{{item.seriesName}}</text>
<text>{{item.value}}</text>
</view>
</view>
</view>
</view>
</view>
</template>
<script>
// nvue
// #ifdef VUE2
import * as echarts from '@/uni_modules/lime-echart/static/echarts.min';
// #endif
// #ifdef VUE3
// #ifdef MP
// vue3 使vite umd使使require
const echarts = require('../../static/echarts.min');
// #endif
// #ifndef MP
// vue3 使vite umdnpm
import * as echarts from 'echarts/dist/echarts.esm';
// #endif
// #endif
export default {
data() {
return {
showTip: false,
position: [],
params: [],
option: {
tooltip: {
trigger: 'axis',
// shadowBlur: 0,
textStyle: {
textShadowBlur : 0
},
renderMode: 'richText',
position: (point, params, dom, rect, size) => {
// tooltips
const box = [170, 170]
//
const offsetX = point[0] < size.viewSize[0] / 2 ? 20 : -box[0] - 20;
const offsetY = point[1] < size.viewSize[1] / 2 ? 20 : -box[1] - 20;
const x = point[0] + offsetX;
const y = point[1] + offsetY;
this.position = [x, y]
this.params = params
},
formatter: (params, ticket, callback) => {
}
},
legend: {
data: ['邮件营销', '联盟广告', '视频广告', '直接访问', '搜索引擎']
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis: {
type: 'category',
boundaryGap: false,
data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
},
yAxis: {
type: 'value'
},
series: [
{
name: '邮件营销',
type: 'line',
stack: '总量',
data: [120, 132, 101, 134, 90, 230, 210]
},
{
name: '联盟广告',
type: 'line',
stack: '总量',
data: [220, 182, 191, 234, 290, 330, 310]
},
{
name: '视频广告',
type: 'line',
stack: '总量',
data: [150, 232, 201, 154, 190, 330, 410]
},
{
name: '直接访问',
type: 'line',
stack: '总量',
data: [320, 332, 301, 334, 390, 330, 320]
},
{
name: '搜索引擎',
type: 'line',
stack: '总量',
data: [820, 932, 901, 934, 1290, 1330, 1320]
}
]
}
}
},
methods: {
init() {
this.$refs.chart.init(echarts, chart => {
chart.setOption(this.option);
// tooltip
chart.on('showTip', (params) => {
this.showTip = true
});
chart.on('hideTip', (params) => {
setTimeout(() => {
this.showTip = false
},300)
});
});
},
save() {
this.$refs.chart.canvasToTempFilePath({
success(res) {
console.log('res::::', res)
}
})
}
}
}
</script>
<style>
.customTooltips {
position: absolute;
background-color: rgba(255, 255, 255, 0.8);
padding: 20rpx;
}
</style>

View File

@ -0,0 +1,88 @@
{
"id": "lime-echart",
"displayName": "echarts",
"version": "0.8.1",
"description": "echarts 全端兼容一款使echarts图表能跑在uniapp各端中的插件",
"keywords": [
"echarts",
"canvas",
"图表",
"可视化"
],
"repository": "https://gitee.com/liangei/lime-echart",
"engines": {
"HBuilderX": "^3.6.4"
},
"dcloudext": {
"sale": {
"regular": {
"price": "0.00"
},
"sourcecode": {
"price": "0.00"
}
},
"contact": {
"qq": ""
},
"declaration": {
"ads": "无",
"data": "无",
"permissions": "无"
},
"npmurl": "",
"type": "component-vue"
},
"uni_modules": {
"dependencies": [],
"encrypt": [],
"platforms": {
"cloud": {
"tcb": "y",
"aliyun": "y"
},
"client": {
"App": {
"app-vue": "y",
"app-nvue": "y"
},
"H5-mobile": {
"Safari": "y",
"Android Browser": "y",
"微信浏览器(Android)": "y",
"QQ浏览器(Android)": "y"
},
"H5-pc": {
"Chrome": "u",
"IE": "u",
"Edge": "u",
"Firefox": "u",
"Safari": "u"
},
"小程序": {
"微信": "y",
"阿里": "y",
"百度": "y",
"字节跳动": "y",
"QQ": "y",
"钉钉": "u",
"快手": "u",
"飞书": "u",
"京东": "u"
},
"快应用": {
"华为": "u",
"联盟": "u"
},
"Vue": {
"vue2": "y",
"vue3": "y"
}
}
}
},
"dependencies": {
"echarts": "^5.4.1",
"zrender": "^5.4.3"
}
}

View File

@ -0,0 +1,42 @@
lockfileVersion: 5.4
specifiers:
echarts: ^5.4.1
zrender: ^5.4.3
dependencies:
echarts: registry.npmmirror.com/echarts/5.4.1
zrender: registry.npmmirror.com/zrender/5.4.3
packages:
registry.npmmirror.com/echarts/5.4.1:
resolution: {integrity: sha512-9ltS3M2JB0w2EhcYjCdmtrJ+6haZcW6acBolMGIuf01Hql1yrIV01L1aRj7jsaaIULJslEP9Z3vKlEmnJaWJVQ==, registry: https://registry.npm.taobao.org/, tarball: https://registry.npmmirror.com/echarts/-/echarts-5.4.1.tgz}
name: echarts
version: 5.4.1
dependencies:
tslib: registry.npmmirror.com/tslib/2.3.0
zrender: registry.npmmirror.com/zrender/5.4.1
dev: false
registry.npmmirror.com/tslib/2.3.0:
resolution: {integrity: sha512-N82ooyxVNm6h1riLCoyS9e3fuJ3AMG2zIZs2Gd1ATcSFjSA23Q0fzjjZeh0jbJvWVDZ0cJT8yaNNaaXHzueNjg==, registry: https://registry.npm.taobao.org/, tarball: https://registry.npmmirror.com/tslib/-/tslib-2.3.0.tgz}
name: tslib
version: 2.3.0
dev: false
registry.npmmirror.com/zrender/5.4.1:
resolution: {integrity: sha512-M4Z05BHWtajY2241EmMPHglDQAJ1UyHQcYsxDNzD9XLSkPDqMq4bB28v9Pb4mvHnVQ0GxyTklZ/69xCFP6RXBA==, registry: https://registry.npm.taobao.org/, tarball: https://registry.npmmirror.com/zrender/-/zrender-5.4.1.tgz}
name: zrender
version: 5.4.1
dependencies:
tslib: registry.npmmirror.com/tslib/2.3.0
dev: false
registry.npmmirror.com/zrender/5.4.3:
resolution: {integrity: sha512-DRUM4ZLnoaT0PBVvGBDO9oWIDBKFdAVieNWxWwK0niYzJCMwGchRk21/hsE+RKkIveH3XHCyvXcJDkgLVvfizQ==, registry: https://registry.npm.taobao.org/, tarball: https://registry.npmmirror.com/zrender/-/zrender-5.4.3.tgz}
name: zrender
version: 5.4.3
dependencies:
tslib: registry.npmmirror.com/tslib/2.3.0
dev: false

View File

@ -0,0 +1,332 @@
# echarts 图表 <span style="font-size:16px;">👑👑👑👑👑 <span style="background:#ff9d00;padding:2px 4px;color:#fff;font-size:10px;border-radius: 3px;">全端</span></span>
> 一个基于 JavaScript 的开源可视化图表库 [查看更多 站点1](https://limeui.qcoon.cn/#/echart) | [查看更多 站点2](http://liangei.gitee.io/limeui/#/echart) <br>
> 基于 echarts 做了兼容处理,更多示例请访问 [uni示例 站点1](https://limeui.qcoon.cn/#/echart-example) | [uni示例 站点2](http://liangei.gitee.io/limeui/#/echart-example) | [官方示例](https://echarts.apache.org/examples/zh/index.html) <br>
> Q群1046793420 <br>
## 平台兼容
| H5 | 微信小程序 | 支付宝小程序 | 百度小程序 | 头条小程序 | QQ 小程序 | App |
| --- | ---------- | ------------ | ---------- | ---------- | --------- | ---- |
| √ | √ | √ | √ | √ | √ | √ |
## 安装
- 第一步、在uniapp 插件市场 找到 [百度图表](https://ext.dcloud.net.cn/plugin?id=4899) 导入
- 第二步、安装 echarts 或者直接使用插件内的echarts.min文件
```cmd
pnpm add echarts
-or-
npm install echarts
```
**注意**
* 🔔 必须使用hbuilderx 3.4.8-alpha及以上
* 🔔 echarts 5.3.0及以上
* 🔔 如果是 `cli` 项目需要主动 `import` 插件
```js
import LEchart from '@/uni_modules/lime-echart/components/l-echart/l-echart.vue';
export default {
components: {LEchart}
}
```
## 代码演示
### 基础用法
```html
<view><l-echart ref="chart" @finished="init"></l-echart></view>
```
```js
// 方式一:自定义包
// 使用插件内提供的echarts.min
// 或在官网自定义包https://echarts.apache.org/zh/builder.html
// 注意 插件内的包是umd格式的如果你是vue3请使用esm格式的包 https://github.com/apache/echarts/tree/master/dist
import * as echarts from '@/uni_modules/lime-echart/static/echarts.min'
// 方式二:全量包
// 如果你使用 npm 安装了 echarts
import * as echarts from 'echarts'
// 方式三:按需引入
// 按需引入 开始
import * as echarts from 'echarts/core';
import {LineChart, BarChart} from 'echarts/charts';
import {TitleComponent,TooltipComponent,GridComponent, DatasetComponent, TransformComponent, LegendComponent } from 'echarts/components';
// 标签自动布局,全局过渡动画等特性
import {LabelLayout,UniversalTransition} from 'echarts/features';
// 引入 Canvas 渲染器,注意引入 CanvasRenderer 是必须的一步
import {CanvasRenderer} from 'echarts/renderers';
// 按需引入 注册必须的组件
echarts.use([
LegendComponent,
TitleComponent,
TooltipComponent,
GridComponent,
DatasetComponent,
TransformComponent,
LineChart,
BarChart,
LabelLayout,
UniversalTransition,
CanvasRenderer
]);
//-------------按需引入结束------------------------
export default {
data() {
return {
option: {
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow'
},
confine: true
},
legend: {
data: ['热度', '正面', '负面']
},
grid: {
left: 20,
right: 20,
bottom: 15,
top: 40,
containLabel: true
},
xAxis: [
{
type: 'value',
axisLine: {
lineStyle: {
color: '#999999'
}
},
axisLabel: {
color: '#666666'
}
}
],
yAxis: [
{
type: 'category',
axisTick: { show: false },
data: ['汽车之家', '今日头条', '百度贴吧', '一点资讯', '微信', '微博', '知乎'],
axisLine: {
lineStyle: {
color: '#999999'
}
},
axisLabel: {
color: '#666666'
}
}
],
series: [
{
name: '热度',
type: 'bar',
label: {
normal: {
show: true,
position: 'inside'
}
},
data: [300, 270, 340, 344, 300, 320, 310],
},
{
name: '正面',
type: 'bar',
stack: '总量',
label: {
normal: {
show: true
}
},
data: [120, 102, 141, 174, 190, 250, 220]
},
{
name: '负面',
type: 'bar',
stack: '总量',
label: {
normal: {
show: true,
position: 'left'
}
},
data: [-20, -32, -21, -34, -90, -130, -110]
}
]
},
};
},
// 组件能被调用必须是组件的节点已经被渲染到页面上
// 1、在页面mounted里调用有时候mounted 组件也未必渲染完成
mounted() {
// init(echarts, theme?:string, opts?:{}, chart => {})
// echarts 必填, 非nvue必填nvue不用填
// theme 可选,应用的主题,目前只支持名称,如:'dark'
// opts = { // 可选
// locale?: string // 从 `5.0.0` 开始支持
// }
// chart => {} callback 返回图表实例
this.$refs.chart.init(echarts, chart => {
chart.setOption(this.option);
});
},
// 2、或者使用组件的finished事件里调用
methods: {
async init() {
// chart 图表实例不能存在data里
const chart = await this.$refs.chart.init(echarts);
chart.setOption(this.option)
}
}
}
```
## 数据更新
- 使用 `ref` 可获取`setOption`设置更新
```js
this.$refs.chart.setOption(data)
```
## 图表大小
- 在有些场景下,我们希望当容器大小改变时,图表的大小也相应地改变。
```js
// 默认获取容器尺寸
this.$refs.chart.resize()
// 指定尺寸
this.$refs.chart.resize({width: 375, height: 375})
```
## 自定义Tooltips
- nvue 不支持
由于除H5之外都不存在dom但又有tooltips个性化的需求代码就不贴了看示例吧
```
代码位于/uni_modules/lime-echart/component/lime-echart
```
## 插件标签
- 默认 l-echart 为 component
- 默认 lime-echart 为 demo
```html
// 在任意地方使用可查看domo, 代码位于/uni_modules/lime-echart/component/lime-echart
<lime-echart></lime-echart>
```
## 常见问题
- 钉钉小程序 由于没有`measureText`,模拟的`measureText`又无法得到当前字体的`fontWeight`,故可能存在估计不精细的问题
- 微信小程序 `2d` 只支持 真机调试2.0
- 微信开发工具会出现 `canvas` 不跟随页面的情况,真机不影响
- 微信开发工具会出现 `canvas` 层级过高的问题,真机一般不受影响,可以先测只有两个元素的页面看是否会有层级问题。
- toolbox 不支持 `saveImage`
- echarts 5.3.0 的 lines 不支持 trailLength故需设置为 `0`
- dataZoom H5不要设置 `showDetail`
- 如果微信小程序的`tooltip`文字有阴影,可能是微信的锅,临时解决方法是`tooltip.shadowBlur = 0`
- 如果钉钉小程序上传时报安全问题`Uint8Clamped`,可以向钉钉反馈是安全代码扫描把Uint8Clamped数组错误识别了也可以在 echarts 文件修改`Uint8Clamped`
```js
// 找到这段代码把代码中`Uint8Clamped`改成`Uint8_Clamped`,再把下划线去掉,不过直接去掉`Uint8Clamped`也是可行的
// ["Int8","Uint8","Uint8Clamped","Int16","Uint16","Int32","Uint32","Float32","Float64"],(function(t,e){return t["[object "+e+"Array]"]
// 改成如下
["Int8","Uint8","Uint8_Clamped","Int16","Uint16","Int32","Uint32","Float32","Float64"],(function(t,e){return t["[object "+e.replace('_','')+"Array]"]
```
### vue3
如果您是使用 **vite + vue3** 非微信小程序可能会遇到`echarts`文件缺少`wx`判断导致无法使用或缺少`tooltip`<br>
方式一:可以在`echarts.min.js`文件开头增加以下内容参考插件内的echart.min.js的做法
```js
var prefix = () => {
var UNDEFINED = 'undefined'
if(typeof wx !== UNDEFINED) return wx // 微信
if(typeof tt !== UNDEFINED) return tt // 字节 飞书
if(typeof swan !== UNDEFINED) return swan // 百度
if(typeof my !== UNDEFINED) return my // 支付宝
if(typeof dd !== UNDEFINED) return dd // 钉钉
if(typeof ks !== UNDEFINED) return ks // 快手
if(typeof jd !== UNDEFINED) return jd // 京东
if(typeof qa !== UNDEFINED) return qa // 快应用
if(typeof qq !== UNDEFINED) return qq // qq
if(typeof qh !== UNDEFINED) return qh // 360
if(typeof uni !== UNDEFINED) return uni
return null
}
//在 !function(t,e){"object"==typeof 下面加入 可能是第36行
var wx = prefix();
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
```
方式二:在`vite.config.js`的`define`设置环境
```js
// 或者在`vite.config.js`的`define`设置环境
import { defineConfig } from 'vite';
import uni from '@dcloudio/vite-plugin-uni';
const UNI_PLATFORM = {
"app": "uni",
"web": "uni",
"mp-weixin": "wx",
"mp-baidu": "swan",
"mp-alipay": "my",
"mp-toutiao": "tt",
"mp-lark": "tt",
"mp-qq": "qq",
"mp-kuaishou": "ks",
"mp-jd": "jd",
"mp-360": "qh",
"quickapp-webview-union": "qa",
"quickapp-webview-huawei": "qa",
"quickapp-webview": "qa",
}
export default defineConfig({
plugins: [uni()],
define: {
global: UNI_PLATFORM[process.env.UNI_PLATFORM],
wx: UNI_PLATFORM[process.env.UNI_PLATFORM]
}
});
```
## Props
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --------------- | -------- | ------- | ------------ | ----- |
| custom-style | 自定义样式 | `string` | - | - |
| type | 指定 canvas 类型 | `string` | `2d` | |
| is-disable-scroll | 触摸图表时是否禁止页面滚动 | `boolean` | `false` | |
| beforeDelay | 延迟初始化 (毫秒) | `number` | `30` | |
| enableHover | PC端使用鼠标悬浮 | `boolean` | `false` | |
## 事件
| 参数 | 说明 |
| --------------- | --------------- |
| init(echarts, chart => {}) | 初始化调用函数,第一个参数是传入`echarts`,第二个参数是回调函数,回调函数的参数是 `chart` 实例 |
| setChart(chart => {}) | 已经初始化后,请使用这个方法,是个回调函数,参数是 `chart` 实例 |
| setOption(data) | [图表配置项](https://echarts.apache.org/zh/option.html#title),用于更新 ,传递是数据 `option` |
| clear() | 清空当前实例,会移除实例中所有的组件和图表。 |
| dispose() | 销毁实例 |
| showLoading() | 显示加载 |
| hideLoading() | 隐藏加载 |
| [canvasToTempFilePath](https://uniapp.dcloud.io/api/canvas/canvasToTempFilePath.html#canvastotempfilepath)(opt) | 用于生成图片,与官方使用方法一致,但不需要传`canvasId` |
## 打赏
如果你觉得本插件,解决了你的问题,赠人玫瑰,手留余香。
![](https://testingcf.jsdelivr.net/gh/liangei/image@1.9/alipay.png)
![](https://testingcf.jsdelivr.net/gh/liangei/image@1.9/wpay.png)

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,129 @@
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title></title>
<style type="text/css">
html,
body,
.canvas {
padding: 0;
margin: 0;
overflow-y: hidden;
background-color: transparent;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div class="canvas" id="limeChart"></div>
<script type="text/javascript" src="./uni.webview.1.5.3.js"></script>
<script type="text/javascript" src="./echarts.min.js"></script>
<script type="text/javascript" src="./ecStat.min.js"></script>
<!-- <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/echarts-liquidfill@latest/dist/echarts-liquidfill.min.js"></script> -->
<script>
let chart = null;
let cache = [];
console.log = function(...agrs) {
postMessage(agrs)
}
function emit(event, data) {
let dataStr = JSON.stringify(data, stringify)
postMessage({
event,
data: dataStr
})
cache = []
}
function postMessage(data) {
uni.postMessage({
data
});
}
function stringify(key, value) {
if (typeof value === 'object' && value !== null) {
if (cache.indexOf(value) !== -1) {
return;
}
cache.push(value);
}
return value;
}
function parse(name, callback, options) {
const optionNameReg = /[\w]+\.setOption\(([\w]+\.)?([\w]+)\)/
if (optionNameReg.test(callback)) {
const optionNames = callback.match(optionNameReg)
if(optionNames[1]) {
const _this = optionNames[1].split('.')[0]
window[_this] = {}
window[_this][optionNames[2]] = options
return optionNames[2]
} else {
return null
}
}
return null
}
function init(callback, options, opts = {}, theme = null) {
if(!chart) {
chart = echarts.init(document.getElementById('limeChart'), theme, opts)
if(options) {
chart.setOption(options)
}
// const name = parse('a', callback, options)
// console.log('options::', callback)
// if(name) this[name] = options
// eval(`a = ${callback};`)
// if(a) {a(chart)}
}
}
function setChart(callback, options) {
if(!callback) return
if(chart && callback && options) {
var r = null
const name = parse('r', callback, options)
if(name) this[name] = options
eval(`r = ${callback};`)
if(r) {r(chart)}
}
}
function setOption(data) {
if (chart) chart.setOption(data[0], data[1])
}
function showLoading(data) {
if (chart) chart.showLoading(data[0], data[1])
}
function hideLoading() {
if (chart) chart.hideLoading()
}
function clear() {
if (chart) chart.clear()
}
function dispose() {
if (chart) chart.dispose()
}
function resize(size) {
if (chart) chart.resize(size)
}
function canvasToTempFilePath(opt = {}) {
if (chart) {
const src = chart.getDataURL(opt)
postMessage({
file: true,
data: src
})
}
}
</script>
</body>
</html>

File diff suppressed because one or more lines are too long

View File

@ -1,169 +0,0 @@
# 在微信小程序中使用 ECharts
> 本项目是 ECharts 的 Mpvue 小程序版本。开发者可以通过熟悉的 ECharts 配置方式及 Vue 语法,快速开发图表,满足各种可视化需求。
[![npm package](https://img.shields.io/npm/v/mpvue-echarts.svg)](https://npmjs.org/package/mpvue-echarts)
[![npm downloads](https://img.shields.io/npm/dm/mpvue-echarts.svg)](https://npmjs.org/package/mpvue-echarts)
## 扫码体验
## 安装
``` bash
npm i mpvue-echarts
```
## 使用
``` vue
<template>
<div class="echarts-wrap">
<mpvue-echarts :echarts="echarts" :onInit="onInit" canvasId="demo-canvas" />
</div>
</template>
<script>
import echarts from 'echarts'
import mpvueEcharts from 'mpvue-echarts'
let chart = null;
function initChart(canvas, width, height) {
chart = echarts.init(canvas, null, {
width: width,
height: height
});
canvas.setChart(chart);
var option = {}; // ECharts 配置项
chart.setOption(option);
return chart; // 返回 chart 后可以自动绑定触摸操作
}
export default {
components: {
mpvueEcharts
},
data () {
return {
echarts,
onInit: initChart
}
}
}
</script>
<style scoped>
.echarts-wrap {
width: 100%;
height: 300px;
}
</style>
```
这对于所有 ECharts 图表都是通用的,用户只需要修改上面 `option` 的内容,即可改变图表。`option` 的使用方法参见 [ECharts 配置项文档](http://echarts.baidu.com/option.html)。对于不熟悉 ECharts 的用户,可以参见 [5 分钟上手 ECharts](http://echarts.baidu.com/tutorial.html#5%20%E5%88%86%E9%92%9F%E4%B8%8A%E6%89%8B%20ECharts) 教程。
## 属性
| 名称 | 类型 | 默认值 | 描述 |
| -------------|--------------- | ------------- | ------------- |
| echarts | Object | null | echarts 对象 |
| canvasId | String | ec-canvas | canvasId |
| onInit | Function | null | 初始化函数 |
| lazyLoad | Boolean | false | 懒加载 |
| disableTouch | Boolean | false | 禁用触摸事件 |
| throttleTouch| Boolean | false | 节流触摸事件 |
## FAQ
### [重要] 不要把 chart 实例赋值到 thisvue 实例) 上
### 如何获取图表实例?
`echarts.init` 返回的即为图表实例。
### 打包结果超过小程序大小限制?
使用自定义版 echarts[官网定制](http://echarts.baidu.com/builder.html)
### 如何延迟加载图表?
参见 [examples/lazyLoad](./examples/src/pages/demos/lazyLoad.vue) 的例子,可以在获取数据后再初始化数据。
### 如何在一个页面中加载多个图表?
参见 [examples/multiCharts](./examples/src/pages/demos/multiCharts.vue) 的例子。
### 图表变空白?
尝试设置 `throttleTouch` 属性为 `true`
### 如何使用 Tooltip
目前,本项目已支持 ECharts Tooltip但是由于 ECharts 相关功能尚未发版,因此当前需要使用原项目中 `ec-canvas/echarts.js`,这个文件包含了可以在微信中使用 Tooltip 的相关代码。目前在 ECharts 官网下载的 `echarts.js` 还不能直接替换使用,等 ECharts 正式发版后即可。
具体使用方法和 ECharts 相同,例子参见 `pages/line/index.js`
### 文件太大怎么办?
本项目默认提供的 ECharts 文件是最新版本的包含所有组件文件,为了便于开发,提供的是未压缩的版本。远程调试或预览可以下载 [echarts.min.js](https://github.com/apache/incubator-echarts/blob/master/dist/echarts.min.js) 压缩版本。
发布时,如果对文件大小要求更高,可以在 [ECharts 在线定制](http://echarts.baidu.com/builder.html)网页下载仅包含必要组件的包,并且选择压缩。
### 打包时出错 `ERROR in static/js/vendor.js from UglifyJs`
参照以下配置使 babel 处理 mpvue-echarts
``` js
// webpack.base.conf.js
{
test: /\.js$/,
include: [
resolve('src'),
resolve('node_modules/mpvue-echarts')
],
use: [
'babel-loader',
{
loader: 'mpvue-loader',
options: {
checkMPEntry: true
}
}
]
}
```
## 微信版本要求
支持微信版本 >= 6.6.3,对应基础库版本 >= 1.9.91。尽可能使用更高版本的基础库版本。
调试的时候,需要在微信开发者工具中,将“详情”下的“调试基础库”设为 1.9.91 及以上版本。
发布前,需要在 [https://mp.weixin.qq.com](https://mp.weixin.qq.com) 的“设置”页面,将“基础库最低版本设置”设为 1.9.91。当用户微信版本过低的时候,会提示用户更新。
## 暂不支持的功能
ECharts 中的绝大部分功能都支持小程序版本,因此这里仅说明不支持的功能,以及存在的问题。
以下功能尚不支持,如果有相关需求请在 [issue](https://github.com/ecomfe/echarts-for-weixin/issues) 中向我们反馈,对于反馈人数多的需求将优先支持:
- 图片
- 多个 zlevel 分层
此外,目前还有一些 bug 尚未修复,部分需要小程序团队配合上线支持,但不影响基本的使用。已知的 bug 包括:
- 安卓平台transform 的问题(会影响关系图边两端的标记位置、旭日图文字位置等)
- iOS 平台:半透明略有变深的问题
- iOS 平台:渐变色出现在定义区域之外的地方
如有其它问题,也欢迎在 [issue](https://github.com/ecomfe/echarts-for-weixin/issues) 中向我们反馈,谢谢!

View File

@ -1,67 +0,0 @@
{
"_from": "mpvue-echarts",
"_id": "mpvue-echarts@0.3.1",
"_inBundle": false,
"_integrity": "sha512-O7IIyvi9TxcaXJDQuJsiDy6UefTTXF//VFgi3GCCyZ0WSBoPcyU0MpvfeMCPPafl8JxTDIgmlr4cZIxmyozSrA==",
"_location": "/mpvue-echarts",
"_phantomChildren": {},
"_requested": {
"type": "tag",
"registry": true,
"raw": "mpvue-echarts",
"name": "mpvue-echarts",
"escapedName": "mpvue-echarts",
"rawSpec": "",
"saveSpec": null,
"fetchSpec": "latest"
},
"_requiredBy": [
"#USER",
"/"
],
"_resolved": "https://registry.npmjs.org/mpvue-echarts/-/mpvue-echarts-0.3.1.tgz",
"_shasum": "4c5baee4c9e89260ab2944ba504527598da7211e",
"_spec": "mpvue-echarts",
"_where": "E:\\project\\uni-app\\echartsTest",
"author": {
"name": "F-loat",
"email": "chaimaoyuan@foxmail.com"
},
"bugs": {
"url": "https://github.com/F-loat/mpvue-echarts/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "适用于 Mpvue 的 ECharts 组件",
"devDependencies": {
"babel-eslint": "^8.2.2",
"eslint": "^4.19.1",
"eslint-config-airbnb-base": "^12.1.0",
"eslint-friendly-formatter": "^4.0.1",
"eslint-plugin-html": "^4.0.3",
"eslint-plugin-import": "^2.10.0"
},
"files": [
"src",
"types"
],
"homepage": "https://github.com/F-loat/mpvue-echarts#readme",
"keywords": [
"mpvue",
"echarts",
"wxapp"
],
"license": "MIT",
"main": "src/echarts.vue",
"name": "mpvue-echarts",
"repository": {
"type": "git",
"url": "git+https://github.com/F-loat/mpvue-echarts.git"
},
"scripts": {
"lint": "eslint --format node_modules/eslint-friendly-formatter --ext .js,.vue src",
"test": "echo \"Error: no test specified\" && exit 1"
},
"typings": "types/index.d.ts",
"version": "0.3.1"
}

View File

@ -1,135 +0,0 @@
<template>
<canvas v-if="canvasId" class="ec-canvas" :id="canvasId" :canvasId="canvasId" @touchstart="touchStart" @touchmove="touchMove"
@touchend="touchEnd" @error="error"></canvas>
</template>
<script>
import WxCanvas from './wx-canvas';
export default {
props: {
canvasId: {
type: String,
default: 'ec-canvas'
},
lazyLoad: {
type: Boolean,
default: false
},
disableTouch: {
type: Boolean,
default: false
},
throttleTouch: {
type: Boolean,
default: false
}
},
// #ifdef H5
mounted() {
if (!this.lazyLoad) this.init();
},
// #endif
// #ifndef H5
onReady() {
if (!this.lazyLoad) this.init();
},
// #endif
methods: {
setChart(chart) {
this.chart = chart
},
init() {
const {
canvasId
} = this;
this.ctx = wx.createCanvasContext(canvasId, this);
this.canvas = new WxCanvas(this.ctx, canvasId);
const query = wx.createSelectorQuery().in(this);
query
.select(`#${canvasId}`)
.boundingClientRect(res => {
if (!res) {
setTimeout(() => this.init(), 50);
return;
}
this.$emit('onInit', {
canvas: this.canvas,
width: res.width,
height: res.height
});
})
.exec();
},
canvasToTempFilePath(opt) {
const {
canvasId
} = this;
this.ctx.draw(true, () => {
wx.canvasToTempFilePath({
canvasId,
...opt
});
});
},
touchStart(e) {
const {
disableTouch,
chart
} = this;
if (disableTouch || !chart || !e.mp.touches.length) return;
const touch = e.mp.touches[0];
chart._zr.handler.dispatch('mousedown', {
zrX: touch.x,
zrY: touch.y
});
chart._zr.handler.dispatch('mousemove', {
zrX: touch.x,
zrY: touch.y
});
},
touchMove(e) {
const {
disableTouch,
throttleTouch,
chart,
lastMoveTime
} = this;
if (disableTouch || !chart || !e.mp.touches.length) return;
if (throttleTouch) {
const currMoveTime = Date.now();
if (currMoveTime - lastMoveTime < 240) return;
this.lastMoveTime = currMoveTime;
}
const touch = e.mp.touches[0];
chart._zr.handler.dispatch('mousemove', {
zrX: touch.x,
zrY: touch.y
});
},
touchEnd(e) {
const {
disableTouch,
chart
} = this;
if (disableTouch || !chart) return;
const touch = e.mp.changedTouches ? e.mp.changedTouches[0] : {};
chart._zr.handler.dispatch('mouseup', {
zrX: touch.x,
zrY: touch.y
});
chart._zr.handler.dispatch('click', {
zrX: touch.x,
zrY: touch.y
});
}
}
};
</script>
<style scoped>
.ec-canvas {
width: 100%;
height: 100%;
flex: 1;
}
</style>

View File

@ -1,73 +0,0 @@
export default class WxCanvas {
constructor(ctx, canvasId) {
this.ctx = ctx;
this.canvasId = canvasId;
this.chart = null;
WxCanvas.initStyle(ctx);
this.initEvent();
}
getContext(contextType) {
return contextType === '2d' ? this.ctx : null;
}
setChart(chart) {
this.chart = chart;
}
attachEvent() {
// noop
}
detachEvent() {
// noop
}
static initStyle(ctx) {
const styles = ['fillStyle', 'strokeStyle', 'globalAlpha',
'textAlign', 'textBaseAlign', 'shadow', 'lineWidth',
'lineCap', 'lineJoin', 'lineDash', 'miterLimit', 'fontSize'];
styles.forEach((style) => {
Object.defineProperty(ctx, style, {
set: (value) => {
if ((style !== 'fillStyle' && style !== 'strokeStyle')
|| (value !== 'none' && value !== null)
) {
ctx[`set${style.charAt(0).toUpperCase()}${style.slice(1)}`](value);
}
},
});
});
ctx.createRadialGradient = () => ctx.createCircularGradient(arguments);
}
initEvent() {
this.event = {};
const eventNames = [{
wxName: 'touchStart',
ecName: 'mousedown',
}, {
wxName: 'touchMove',
ecName: 'mousemove',
}, {
wxName: 'touchEnd',
ecName: 'mouseup',
}, {
wxName: 'touchEnd',
ecName: 'click',
}];
eventNames.forEach((name) => {
this.event[name.wxName] = (e) => {
const touch = e.mp.touches[0];
this.chart.getZr().handler.dispatch(name.ecName, {
zrX: name.wxName === 'tap' ? touch.clientX : touch.x,
zrY: name.wxName === 'tap' ? touch.clientY : touch.y,
});
};
});
}
}

View File

@ -1,11 +0,0 @@
import Vue from 'vue'
/** Echarts Component */
export declare class Ecahrts extends Vue {
echarts: object
onInit?: () => object
canvasId?: string
lazyLoad?: boolean
disableTouch?: boolean
throttleTouch?: boolean
}

View File

@ -1,3 +0,0 @@
import { Ecahrts } from './echarts'
export default Ecahrts

View File

@ -1,6 +1,20 @@
<template>
<view class="cont">
<div class="tab" @tap.stop="changeTabbar(0)">
<image src="@/static/tabbar/home.png" mode="" v-show="indexs!=0"></image>
<image src="@/static/tabbar/home-active.png" mode="" v-show="indexs==0"></image>
<div class="txt" :class="indexs==0?'act1':''">首页</div>
</div>
<div class="tab" @tap.stop="changeTabbar(1)">
<image src="@/static/tabbar/tj.png" mode="" v-show="indexs!=1" style="width: 36rpx;height: 36rpx;"></image>
<image src="@/static/tabbar/tj-active.png" mode="" v-show="indexs==1" style="width: 36rpx;height: 36rpx;"></image>
<div class="txt" :class="indexs==1?'act1':''">统计</div>
</div>
<div class="tab" @tap.stop="changeTabbar(2)">
<image src="@/static/tabbar/my.png" mode="" v-show="indexs!=2" style="width: 28rpx;height: 36.4rpx;"></image>
<image src="@/static/tabbar/my-active.png" mode="" v-show="indexs==2" style="width: 28rpx;height: 36.4rpx;"></image>
<div class="txt" :class="indexs==2?'act1':''">我的</div>
</div>
<!-- <view class="u-page">
</view> -->
@ -32,6 +46,37 @@
// }
// this.changeTabbar(index)
},
methods:{
changeTabbar(index) {
if (this.currentTabbarIndex === index) return
// this._switchTabbarPage(index)
if(index==0){
uni.switchTab({
url:'/pages/index/index',
success() {
this.currentTabbarIndex = index
}
})
console.log('点击了',index);
}else if(index==1){
uni.switchTab({
url:'/pages/tj',
success() {
this.currentTabbarIndex = index
}
})
}else if(index==2){
uni.switchTab({
url:'/pages/my',
success() {
this.currentTabbarIndex = index
}
})
}
},
}
}
</script>
<style lang="scss" scoped>
@ -56,5 +101,28 @@
background: #FFFFFF;
box-shadow: 0rpx 16rpx 40rpx 0rpx rgba(53, 140, 255, 0.1);
border-radius: 60rpx;
display: flex;
align-items: center;
justify-content: space-around;
.tab{
width: 44rpx;
display: flex;
flex-wrap: wrap;
justify-content: center;
image{
width: 30rpx;
height: 30rpx;
}
.txt{
margin-top: 10rpx;
font-size: 20rpx;
font-family: HarmonyOS Sans SC, HarmonyOS Sans SC;
font-weight: 400;
color: #95989D;
}
.act1{
color: #8883F0;
}
}
}
</style>

View File

@ -5,9 +5,10 @@
"pages": [{
"path": "pages/index/index",
"style": {
"navigationBarTitleText": "",
"navigationBarBackgroundColor": "#4473f6",
"navigationBarTitleText": "我的",
"enablePullDownRefresh": false,
"navigationBarBackgroundColor": "#3996FD",
"navigationBarTextStyle": "#FFFFFF",
"navigationStyle": "custom"
}
},
@ -15,16 +16,22 @@
"path" : "pages/tj",
"style" :
{
"navigationBarTitleText" : "",
"enablePullDownRefresh" : false
"navigationBarTitleText": "我的",
"enablePullDownRefresh": false,
"navigationBarBackgroundColor": "#3996FD",
"navigationBarTextStyle": "#FFFFFF",
"navigationStyle": "custom"
}
},
{
"path" : "pages/my",
"style" :
{
"navigationBarTitleText" : "",
"enablePullDownRefresh" : false
"navigationBarTitleText": "我的",
"enablePullDownRefresh": false,
"navigationBarBackgroundColor": "#3996FD",
"navigationBarTextStyle": "#FFFFFF",
"navigationStyle": "custom"
}
}
@ -44,30 +51,31 @@
// ],
// "tabBar": {
// "color": "#a9b7b7",
// "selectedColor": "#5185fd",
// "borderStyle": "white",
// "backgroundColor": "#ffffff",
// "list": [{
// "selectedIconPath": "/static/tabbar/home-active.png",
// "iconPath": "/static/tabbar/home.png",
// "pagePath": "pages/index/index",
// "text": "首页"
// },
// {
// "selectedIconPath": "/static/tabbar/tiku-act.png",
// "iconPath": "/static/tabbar/tiku.png",
// "pagePath": "pages/Mystudent/student",
// "text": "班级"
// }, {
// "selectedIconPath": "/static/tabbar/my-active.png",
// "iconPath": "/static/tabbar/my.png",
// "pagePath": "pages/user/user",
// "text": "我的"
// }
// ]
// },
"tabBar": {
"custom": true,
"color": "#a9b7b7",
"selectedColor": "#5185fd",
"borderStyle": "white",
"backgroundColor": "#ffffff",
"list": [{
"selectedIconPath": "/static/tabbar/home-active.png",
"iconPath": "/static/tabbar/home.png",
"pagePath": "pages/index/index",
"text": "首页"
},
{
"selectedIconPath": "/static/tabbar/tj-active.png",
"iconPath": "/static/tabbar/tj.png",
"pagePath": "pages/tj",
"text": "统计"
}, {
"selectedIconPath": "/static/tabbar/my-active.png",
"iconPath": "/static/tabbar/my.png",
"pagePath": "pages/my",
"text": "我的"
}
]
},
"globalStyle": {
"navigationBarTextStyle": "black",
"navigationBarTitleText": "uni-app",

View File

@ -1,6 +1,6 @@
<template>
<view>
<tab-bar :indexs='2'></tab-bar>
</view>
</template>

View File

@ -1,22 +1,205 @@
<template>
<view>
<view class="page">
<div class="title">
统计
</div>
<div class="card">
<view class="month">
2024年01月
</view>
<view class="tit">
本月用电量
</view>
<div class="txt">
25.36
</div>
<view class="echarts">
<!-- <mpvue-echarts id="main" ref="pieChart" :echarts="echarts" @onInit="initChart" /> -->
<l-echart ref="chart" @finished="initChart"></l-echart>
</view>
</div>
<tab-bar :indexs='1'></tab-bar>
</view>
</template>
<script>
import * as echarts from 'echarts'
import LEchart from '@/uni_modules/lime-echart/components/l-echart/l-echart.vue';
export default {
components: {
LEchart
},
data() {
return {
}
},
onLoad() {
// setTimeout(() => {
// this.initChart()
// }, 300);
// this.initChart()
},
methods: {
generateWaveData(length) {
const data = [];
for (let i = 0; i < length; i++) {
const y = Math.sin((i / (length - 1)) * Math.PI * 2); // y
data.push((y + 1) * 50); // 0-100
}
return data;
},
async initChart() {
console.log('111111');
// let _this = this
const waveData = this.generateWaveData(10);
const option = {
grid: {
left: 10,
right: 10,
top: 10,
bottom: 30,
// containLabel: true,
},
xAxis: {
type: 'category',
boundaryGap: false,
axisLine: {
show: false, // 线
},
axisTick: {
show: false, //
},
axisLabel: {
show: true,
color: '#fff', // x
fontSize: 11, // x
rotate: 90, // 180°
},
splitLine: {
show: false, // 线
},
data: ['1日', '2日', '3日', '4日', '5日', '6日', '7日'], //
},
yAxis: {
show: false,
},
visualMap: {
type: 'piecewise',
show: false,
dimension: 0,
seriesIndex: 0,
pieces: [
{
gt: 1,
lt: 3,
color: 'rgba(0, 0, 180, 0.4)',
},
{
gt: 5,
lt: 7,
color: 'rgba(0, 0, 180, 0.4)',
},
],
},
series: [
{
type: 'line',
smooth: 0.6,
symbol: 'none',
lineStyle: {
color: '#E0DBFF', // 线
width: 4,
},
areaStyle: {
normal: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{ offset: 0, color: '#B4B0F7' },
]),
},
},
data: [200, 560, 3000, 580, 250, 300, 450],
},
],
};
// console.log( this.$refs.chartRef,'1111');
const chart = await this.$refs.chart.init(echarts);
console.log(option);
chart.setOption(option)
return chart
},
}
}
</script>
<style>
<style lang="scss">
page {
background-color: #F7FAFE;
}
</style>
.page {
padding: 0 59rpx;
.title {
margin-top: 170rpx;
font-size: 48rpx;
font-weight: 400;
letter-spacing: 0rpx;
color: rgba(38, 43, 55, 1);
}
.card {
padding-top: 32rpx;
margin-top: 66rpx;
width: 632rpx;
height: 586rpx;
background: #8883F0;
box-shadow: 0rpx 16rpx 40rpx 0rpx rgba(42, 130, 228, 0.1);
opacity: 1;
// filter: blur(0px);
border-radius: 40rpx;
.month {
margin-left: 22rpx;
font-size: 28rpx;
font-family: Source Han Sans, Source Han Sans;
font-weight: 400;
color: #FFFFFF;
}
.tit {
margin-top: 18rpx;
margin-left: 22rpx;
font-size: 20rpx;
font-family: HarmonyOS Sans SC, HarmonyOS Sans SC;
font-weight: 400;
color: #FFFFFF;
}
.txt {
margin-top: 2rpx;
margin-left: 22rpx;
font-size: 36rpx;
font-family: HarmonyOS Sans SC, HarmonyOS Sans SC;
font-weight: 700;
color: #FFFFFF;
}
.echarts {
margin-left: 22rpx;
margin-top: 60rpx;
// width: 100%;
// height: 80%;
width: 588rpx;
height: 320rpx;
}
}
}
</style>

Binary file not shown.

After

(image error) Size: 504 B

BIN
static/tabbar/my-active.png Normal file

Binary file not shown.

After

(image error) Size: 576 B

BIN
static/tabbar/tj-active.png Normal file

Binary file not shown.

After

(image error) Size: 489 B

BIN
static/tabbar/tj.png Normal file

Binary file not shown.

After

(image error) Size: 587 B

View File

@ -14,15 +14,7 @@
/* 颜色变量 */
// 引入uview
@font-face {
font-family: 'PingFang';
src: url('https://file.langsi.online/ttf/PingFangSC.ttf') format('truetype');
}
/* 使用全局字体 */
body {
font-family: 'PingFang', 'Helvetica Neue', Arial, sans-serif;
}
@import 'uview-ui/theme.scss';
/* 行为相关颜色 */
$uni-color-primary: #007aff;

View File

@ -1,3 +1,7 @@
## 0.8.32024-01-21
- chore: 更新文档
## 0.8.22024-01-21
- feat: 支持 `uvue`
## 0.8.12023-08-24
- fix: app 的`touch`事件为`object` 导致无法显示 `tooltip`
## 0.8.02023-08-22

View File

@ -0,0 +1,141 @@
<template>
<web-view class="lime-echart" ref="limeEchart" :style="[customStyle]" :webview-styles="[webviewStyles]"
src="/uni_modules/lime-echart/static/uvue.html?v=1011">
</web-view>
</template>
<script lang="uts">
import { Echarts } from './uvue';
type EchartsResolve = (value : Echarts) => void
export default {
name: 'l-echart',
props: {
webviewStyles: {
type: Object
},
customStyle: {
type: Object
},
isDisableScroll: {
type: Boolean,
default: false
},
isClickable: {
type: Boolean,
default: true
},
enableHover: {
type: Boolean,
default: false
},
beforeDelay: {
type: Number,
default: 30
}
},
data() {
return {
finished: false,
map: [] as EchartsResolve[],
context: null as UniWebViewElement | null,
// el: null as UniWebViewElement | null,
chart: null as Echarts | null
};
},
computed: {
},
unmounted() {
},
created() {
},
mounted() {
this.createSelectorQuery().select('.lime-echart').boundingClientRect(_ => {
const context = this.$el as UniWebViewElement
this.context = context
// context.addEventListener('error', (_ : WebViewErrorEvent) => { })
// context.addEventListener('loading', (_ : WebViewLoadingEvent) => { })
context.addEventListener('loaded', (event : WebViewLoadedEvent) => {
this.finished = true
event.stopPropagation()
event.preventDefault()
this.trigger()
this.$emit('finished')
})
}).exec()
},
methods: {
_next() {
if (this.chart == null) {
console.warn(`组件还未初始化,请先使用 init`)
return
}
},
setOption(option : UTSJSONObject) {
this._next()
this.chart?.setOption(option);
},
showLoading() {
this._next()
this.chart?.showLoading();
},
hideLoading() {
this._next()
this.chart?.hideLoading();
},
clear() {
this._next()
this.chart?.clear();
},
dispose() {
this._next()
this.chart?.dispose();
},
resize(size:UTSJSONObject) {
this._next()
this.chart?.resize(size);
},
canvasToTempFilePath(opt: UTSJSONObject) {
this._next()
this.chart?.canvasToTempFilePath(opt)
},
trigger() {
if (this.finished) {
if (this.chart == null) {
this.chart = new Echarts(this.context!)
}
while (this.map.length > 0) {
const resolve = this.map.pop() as EchartsResolve
resolve(this.chart!)
}
}
},
init() : Promise<Echarts> {
return new Promise((resolve) => {
this.map.push(resolve)
this.trigger()
})
},
init(callback : (chart : Echarts) => void) : Promise<Echarts> {
if (this.chart !== null) {
callback(this.chart!)
} else {
console.warn('echarts 未加载完成,您可以延时一下')
}
return new Promise((resolve) => {
this.map.push(resolve)
this.trigger()
})
}
}
};
</script>
<style lang="scss">
.lime-echart {
flex: 1;
}
</style>

View File

@ -54,7 +54,7 @@
:style="canvasStyle"
:webview-styles="webviewStyles"
ref="webview"
src="/uni_modules/lime-echart/static/index.html"
src="/uni_modules/lime-echart/static/nvue.html?v=1"
@pagefinish="finished = true"
@onPostMessage="onMessage"
></web-view>
@ -187,11 +187,15 @@ export default {
// #ifdef APP-NVUE
onMessage(e) {
const res = e?.detail?.data[0] || null;
if (res?.event) {
if (res?.event) {
const data = JSON.parse(res.data)
if(res.event === 'inited') {
this.inited = true
} else if(res.event.startsWith('@')){
this.chart.dispatchAction(res.event.split('@')[1], data.options)
}
this.$emit(res.event, JSON.parse(res.data));
this.$emit(res.event, data);
} else if(res?.file){
this.file = res.data
} else if(!res[0] && JSON.stringify(res[0]) != '{}'){

View File

@ -1,4 +1,5 @@
export class Echarts {
eventMap = new Map()
constructor(webview) {
this.webview = webview
this.options = null
@ -30,6 +31,21 @@ export class Echarts {
}
}
on(type, ...args) {
const query = args[0]
const useQuery = query && typeof query != 'function'
const param = useQuery ? [type, query] : [type]
const key = `${type}${useQuery ? JSON.stringify(query): '' }`
const callback = useQuery ? args[1]: args[0]
if(typeof callback == 'function'){
this.eventMap.set(key, callback)
}
this.webview.evalJs(`on(${JSON.stringify(param)})`);
console.warn('nvue 暂不支持事件')
}
dispatchAction(type, options){
const handler = this.eventMap.get(type)
if(handler){
handler(options)
}
}
}

View File

@ -0,0 +1,105 @@
type EchartsEventHandler = (event: UTSJSONObject)=>void
// type EchartsTempResolve = (obj : UTSJSONObject) => void
// type EchartsTempOptions = UTSJSONObject
export class Echarts {
options: UTSJSONObject = {} as UTSJSONObject
context: UniWebViewElement
eventMap: Map<string, EchartsEventHandler> = new Map()
private temp: UTSJSONObject[] = []
constructor(context: UniWebViewElement){
this.context = context
this.init()
}
init(){
this.context.evalJS(`init(null, null, ${JSON.stringify({})})`)
this.context.addEventListener('message', (e : WebViewMessageEvent) => {
// event.stopPropagation()
// event.preventDefault()
const log = e.detail.data!.get('log')
const event = e.detail.data!.get('event')
const options = e.detail.data!.get('options')
const file = e.detail.data!.get('file')
if (log != null) {
console.log(log)
}
if (event != null && options != null) {
this.dispatchAction(event as string, options as UTSJSONObject)
}
if(file != null){
while (this.temp.length > 0) {
const opt = this.temp.pop()
const success = opt?.get('success')
if(typeof success == 'function'){
success as (res: UTSJSONObject) => void
success({tempFilePath: file})
}
}
}
})
}
setOption(option: UTSJSONObject){
this.options = option;
this.context.evalJS(`setOption(${JSON.stringify([option])})`)
}
setOption(option: UTSJSONObject, notMerge: boolean = false, lazyUpdate: boolean = false){
this.options = option;
this.context.evalJS(`setOption(${JSON.stringify([option, notMerge, lazyUpdate])})`)
}
setOption(option: UTSJSONObject, notMerge: UTSJSONObject){
this.options = option;
this.context.evalJS(`setOption(${JSON.stringify([option, notMerge])})`)
}
getOption(): UTSJSONObject {
return this.options
}
showLoading(){
this.context.evalJS(`showLoading(${JSON.stringify([] as any[])})`);
}
showLoading(type: string, opts: UTSJSONObject){
this.context.evalJS(`showLoading(${JSON.stringify([type, opts])})`);
}
hideLoading(){
this.context.evalJS(`hideLoading()`);
}
clear(){
this.context.evalJS(`clear()`);
}
dispose(){
this.context.evalJS(`dispose()`);
}
resize(size:UTSJSONObject){
this.context.evalJS(`resize(${JSON.stringify(size)})`);
}
resize(){
this.context.evalJS(`resize()`);
}
on(type:string, query: any, callback: EchartsEventHandler) {
const key = `${type}${JSON.stringify(query)}`
if(typeof callback == 'function'){
this.eventMap.set(key, callback)
}
this.context.evalJS(`on(${JSON.stringify([type, query])})`);
console.warn('uvue 暂不支持事件')
}
on(type:string, callback: EchartsEventHandler) {
const key = `${type}`
if(typeof callback == 'function'){
this.eventMap.set(key, callback)
}
this.context.evalJS(`on(${JSON.stringify([type])})`);
console.warn('uvue 暂不支持事件')
}
dispatchAction(type:string, options: UTSJSONObject){
const handler = this.eventMap.get(type)
if(handler!=null){
handler(options)
}
}
canvasToTempFilePath(opt: UTSJSONObject){
this.context.evalJS(`on(${JSON.stringify(opt)})`);
this.temp.push(opt)
}
}

View File

@ -0,0 +1,95 @@
<template>
<view style="width: 100%; height: 408px;">
<l-echart ref="chartRef" @finished="init"></l-echart>
</view>
</template>
<script>
export default {
data() {
return {
showTip: false,
option: {
tooltip: {
trigger: 'axis',
// shadowBlur: 0,
textStyle: {
textShadowBlur: 0
},
renderMode: 'richText',
},
legend: {
data: ['邮件营销', '联盟广告', '视频广告', '直接访问', '搜索引擎']
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis: {
type: 'category',
boundaryGap: false,
data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
},
yAxis: {
type: 'value'
},
series: [
{
name: '邮件营销',
type: 'line',
stack: '总量',
data: [120, 132, 101, 134, 90, 230, 210]
},
{
name: '联盟广告',
type: 'line',
stack: '总量',
data: [220, 182, 191, 234, 290, 330, 310]
},
{
name: '视频广告',
type: 'line',
stack: '总量',
data: [150, 232, 201, 154, 190, 330, 410]
},
{
name: '直接访问',
type: 'line',
stack: '总量',
data: [320, 332, 301, 334, 390, 330, 320]
},
{
name: '搜索引擎',
type: 'line',
stack: '总量',
data: [820, 932, 901, 934, 1290, 1330, 1320]
}
]
}
}
},
mounted() {
console.log('lime echarts nvue')
},
methods: {
init() {
const chartRef = this.$refs['chartRef']
chartRef.init(chart => {
chart.setOption(this.option);
})
},
save() {
// this.$refs.chart.canvasToTempFilePath({
// success(res) {
// console.log('res::::', res)
// }
// })
}
}
}
</script>
<style>
</style>

View File

@ -0,0 +1,96 @@
<template>
<view style="width: 100%; height: 408px;">
<l-echart ref="chartRef" @finished="init"></l-echart>
</view>
</template>
<script lang="uts">
export default {
data() {
return {
showTip: false,
option: {
tooltip: {
trigger: 'axis',
// shadowBlur: 0,
textStyle: {
textShadowBlur: 0
},
renderMode: 'richText',
},
legend: {
data: ['邮件营销', '联盟广告', '视频广告', '直接访问', '搜索引擎']
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis: {
type: 'category',
boundaryGap: false,
data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
},
yAxis: {
type: 'value'
},
series: [
{
name: '邮件营销',
type: 'line',
stack: '总量',
data: [120, 132, 101, 134, 90, 230, 210]
},
{
name: '联盟广告',
type: 'line',
stack: '总量',
data: [220, 182, 191, 234, 290, 330, 310]
},
{
name: '视频广告',
type: 'line',
stack: '总量',
data: [150, 232, 201, 154, 190, 330, 410]
},
{
name: '直接访问',
type: 'line',
stack: '总量',
data: [320, 332, 301, 334, 390, 330, 320]
},
{
name: '搜索引擎',
type: 'line',
stack: '总量',
data: [820, 932, 901, 934, 1290, 1330, 1320]
}
]
}
}
},
mounted() {
console.log('lime echarts uvue')
},
methods: {
init() {
const chartRef = this.$refs['chartRef'] as LEchartComponentPublicInstance
chartRef.init(chart => {
chart.setOption(this.option);
})
},
save() {
// this.$refs.chart.canvasToTempFilePath({
// success(res) {
// console.log('res::::', res)
// }
// })
}
}
}
</script>
<style>
</style>

View File

@ -1,6 +1,6 @@
<template>
<view >
<view style="height: 750rpx; background-color: aquamarine; position: relative">
<view style="height: 750rpx; position: relative">
<l-echart ref="chart" @finished="init"></l-echart>
<view class="customTooltips" :style="{left: position[0] + 'px',top: position[1] + 'px'}" v-if="params.length && position.length && showTip">
<view>这是个自定的tooltips</view>
@ -113,14 +113,28 @@
}
}
},
methods: {
init() {
// init(echarts, theme?:string, opts?:{}, chart => {})
// echarts nvuenvue
// theme 'dark'
// opts = { //
// locale?: string // `5.0.0`
// }
// chart => {} callback
// setTimeout(()=>{
// this.$refs.chart.init(echarts, chart => {
// chart.setOption(this.option);
// });
// },300)
this.$refs.chart.init(echarts, chart => {
chart.setOption(this.option);
// tooltip
chart.on('showTip', (params) => {
this.showTip = true
console.log('showTip::')
});
chart.on('hideTip', (params) => {
setTimeout(() => {

View File

@ -1,7 +1,7 @@
{
"id": "lime-echart",
"displayName": "echarts",
"version": "0.8.1",
"version": "0.8.3",
"description": "echarts 全端兼容一款使echarts图表能跑在uniapp各端中的插件",
"keywords": [
"echarts",
@ -44,7 +44,8 @@
"client": {
"App": {
"app-vue": "y",
"app-nvue": "y"
"app-nvue": "y",
"app-uvue": "y"
},
"H5-mobile": {
"Safari": "y",

View File

@ -11,47 +11,46 @@
## 安装
- 第一步、在uniapp 插件市场 找到 [百度图表](https://ext.dcloud.net.cn/plugin?id=4899) 导入
- 第二步、安装 echarts 或者直接使用插件内的echarts.min文件
- 在市场导入 [百度图表](https://ext.dcloud.net.cn/plugin?id=4899)
**注意**
* 🔔 echarts 5.3.0及以上
* 🔔 如果是 `cli` 项目请下载插件到`src`目录下的`uni_modules`,没有这个目录就创建一个
## 代码演示
### Vue2
```html
<view style="width:750rpx; height:750rpx"><l-echart ref="chartRef" @finished="init"></l-echart></view>
```
#### 方式一:引入插件内的或自定义包
- 引入插件内提供或自己下载的自定义包
- 生成[自定义包](https://github.com/apache/echarts/tree/master/dist)
```js
// 插件内的 二选一
import * as echarts from '@/uni_modules/lime-echart/static/echarts.min'
// 自定义的 二选一
import * as echarts from 'xxx/echarts.min'
```
#### 方式二npm包
- 自行安装 `echarts`
- 可根据自己的需要全量引入或按需引入
```cmd
pnpm add echarts
-or-
npm install echarts
```
**注意**
* 🔔 必须使用hbuilderx 3.4.8-alpha及以上
* 🔔 echarts 5.3.0及以上
* 🔔 如果是 `cli` 项目需要主动 `import` 插件
```js
import LEchart from '@/uni_modules/lime-echart/components/l-echart/l-echart.vue';
export default {
components: {LEchart}
}
```
## 代码演示
### 基础用法
```html
<view><l-echart ref="chart" @finished="init"></l-echart></view>
```
```js
// 方式一:自定义包
// 使用插件内提供的echarts.min
// 或在官网自定义包https://echarts.apache.org/zh/builder.html
// 注意 插件内的包是umd格式的如果你是vue3请使用esm格式的包 https://github.com/apache/echarts/tree/master/dist
import * as echarts from '@/uni_modules/lime-echart/static/echarts.min'
// 方式二:全量包
// 如果你使用 npm 安装了 echarts
// 全量包 二选一
import * as echarts from 'echarts'
// 方式三:按需引入
// 按需引入 开始
// 按需引入 二选一
import * as echarts from 'echarts/core';
import {LineChart, BarChart} from 'echarts/charts';
import {TitleComponent,TooltipComponent,GridComponent, DatasetComponent, TransformComponent, LegendComponent } from 'echarts/components';
@ -74,9 +73,9 @@ echarts.use([
UniversalTransition,
CanvasRenderer
]);
//-------------按需引入结束------------------------
```
```js
export default {
data() {
return {
@ -166,35 +165,117 @@ export default {
};
},
// 组件能被调用必须是组件的节点已经被渲染到页面上
// 1、在页面mounted里调用有时候mounted 组件也未必渲染完成
mounted() {
// init(echarts, theme?:string, opts?:{}, chart => {})
// echarts 必填, 非nvue必填nvue不用填
// theme 可选,应用的主题,目前只支持名称,如:'dark'
// opts = { // 可选
// locale?: string // 从 `5.0.0` 开始支持
// }
// chart => {} callback 返回图表实例
this.$refs.chart.init(echarts, chart => {
chart.setOption(this.option);
});
},
// 2、或者使用组件的finished事件里调用
methods: {
async init() {
// chart 图表实例不能存在data里
const chart = await this.$refs.chart.init(echarts);
const chart = await this.$refs.chartRef.init(echarts);
chart.setOption(this.option)
}
}
}
```
## 数据更新
- 使用 `ref` 可获取`setOption`设置更新
### Vue3
```html
<view style="width:750rpx; height:750rpx"><l-echart ref="chart" @finished="init"></l-echart></view>
```
#### 小程序引入插件内的包或自定义包
- 引入插件内提供或自己下载的自定义包
- 生成[自定义包](https://github.com/apache/echarts/tree/master/dist)
- `require`仅支持相对路径,不支持路径别名
```js
// 插件内的 二选一
const echarts = require('../../uni_modules/lime-echart/static/echarts.min');
// 自定义的 二选一
const echarts = require('xxx/xxx/echarts');
```
#### 非小程序端不支持引入插件内的包
- 由于vue3使用的是vite 不支持非`esm`格式,故不支持引入插件内的包
- 可使用`npm`包
#### 方式二npm包
- 可自行安装 `echarts`
- 可根据自己的需要全量引入或按需引入
```cmd
pnpm add echarts
-or-
npm install echarts
```
```js
// 全量包 二选一
import * as echarts from 'echarts'
// 按需引入 二选一
import * as echarts from 'echarts/core';
import {LineChart, BarChart} from 'echarts/charts';
import {TitleComponent,TooltipComponent,GridComponent, DatasetComponent, TransformComponent, LegendComponent } from 'echarts/components';
// 标签自动布局,全局过渡动画等特性
import {LabelLayout,UniversalTransition} from 'echarts/features';
// 引入 Canvas 渲染器,注意引入 CanvasRenderer 是必须的一步
import {CanvasRenderer} from 'echarts/renderers';
// 按需引入 注册必须的组件
echarts.use([
LegendComponent,
TitleComponent,
TooltipComponent,
GridComponent,
DatasetComponent,
TransformComponent,
LineChart,
BarChart,
LabelLayout,
UniversalTransition,
CanvasRenderer
]);
```
```js
const chartRef = ref(null)
onMounted( ()=>{
// 组件能被调用必须是组件的节点已经被渲染到页面上
setTimeout(async()=>{
if(!chartRef.value) return
const myChart = await chartRef.value.init(echarts)
myChart.setOption(data)
},300)
})
```
### Uvue
- Uvue和Nvue不需要引入`echarts`,因为它们的实现方式是`webview`
```js
methods: {
async init() {
const chartRef = this.$refs['chartRef'] as LEchartComponentPublicInstance
const myChart = await chartRef.init()
myChart.setOption(this.option)
}
}
```
## 数据更新
- 1、使用 `ref` 可获取`setOption`设置更新
- 2、也可以拿到图表实例`chart`设置`myChart.setOption(data)`
```js
// ref
this.$refs.chart.setOption(data)
// 图表实例
myChart.setOption(data)
```
## 图表大小
@ -208,7 +289,7 @@ this.$refs.chart.resize({width: 375, height: 375})
```
## 自定义Tooltips
- nvue 不支持
- uvue\nvue 不支持
由于除H5之外都不存在dom但又有tooltips个性化的需求代码就不贴了看示例吧
```
代码位于/uni_modules/lime-echart/component/lime-echart

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,177 @@
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title></title>
<style type="text/css">
html,
body,
.canvas {
padding: 0;
margin: 0;
overflow-y: hidden;
background-color: transparent;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div class="canvas" id="limeChart"></div>
<script type="text/javascript" src="./uni.webview.1.5.3.js"></script>
<script type="text/javascript" src="./echarts.min.js"></script>
<script type="text/javascript" src="./ecStat.min.js"></script>
<!-- <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/echarts-liquidfill@latest/dist/echarts-liquidfill.min.js"></script> -->
<script>
let chart = null;
let cache = [];
console.log = function(...agrs) {
postMessage(agrs)
}
function emit(event, data) {
let dataStr = JSON.stringify(data, stringify)
postMessage({
event,
data: dataStr
})
cache = []
}
function postMessage(data) {
uni.postMessage({
data
});
}
function stringify(key, value) {
if (typeof value === 'object' && value !== null) {
if (cache.indexOf(value) !== -1) {
return;
}
cache.push(value);
}
return value;
}
function parse(name, callback, options) {
const optionNameReg = /[\w]+\.setOption\(([\w]+\.)?([\w]+)\)/
if (optionNameReg.test(callback)) {
const optionNames = callback.match(optionNameReg)
if (optionNames[1]) {
const _this = optionNames[1].split('.')[0]
window[_this] = {}
window[_this][optionNames[2]] = options
return optionNames[2]
} else {
return null
}
}
return null
}
function init(callback, options, opts = {}, theme = null) {
if (!chart) {
chart = echarts.init(document.getElementById('limeChart'), theme, opts)
if (options) {
chart.setOption(options)
}
// const name = parse('a', callback, options)
// console.log('options::', callback)
// if(name) this[name] = options
// eval(`a = ${callback};`)
// if(a) {a(chart)}
}
}
function setChart(callback, options) {
if (!callback) return
if (chart && callback && options) {
var r = null
const name = parse('r', callback, options)
if (name) this[name] = options
eval(`r = ${callback};`)
if (r) {
r(chart)
}
}
}
function setOption(data) {
if (chart) chart.setOption(data[0], data[1])
}
function showLoading(data) {
if (chart) chart.showLoading(data[0], data[1])
}
function hideLoading() {
if (chart) chart.hideLoading()
}
function clear() {
if (chart) chart.clear()
}
function dispose() {
if (chart) chart.dispose()
}
function resize(size) {
if (chart) chart.resize(size)
}
function canvasToTempFilePath(opt = {}) {
if (chart) {
const src = chart.getDataURL(opt)
postMessage({
file: true,
data: src
})
}
}
function on(data) {
if (chart && data.length > 0) {
const [type, query] = data
const useQuery = query && typeof query != 'function'
const key = `${type}${useQuery ? JSON.stringify(query): '' }`
if (query) {
chart.on(type, query, (options) => {
const obj = {}
Object.keys(options).forEach(key => {
if (key != 'event') {
obj[key] = options[key]
}
})
emit(`@${key}`, {
event: key,
options: obj
})
})
} else {
chart.on(type, (options) => {
const obj = {}
Object.keys(options).forEach(key => {
if (key != 'event') {
obj[key] = options[key]
}
})
emit(`@${key}`, {
event: key,
options: obj
})
})
}
}
}
</script>
</body>
</html>

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,173 @@
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title></title>
<style type="text/css">
html,
body,
.canvas {
padding: 0;
margin: 0;
overflow-y: hidden;
background-color: transparent;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div class="canvas" id="limeChart"></div>
<script type="text/javascript" src="./uni.webview.1.5.5.js"></script>
<script type="text/javascript" src="./echarts.min.js"></script>
<script type="text/javascript" src="./ecStat.min.js"></script>
<!-- <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/echarts-liquidfill@latest/dist/echarts-liquidfill.min.js"></script> -->
<script>
let chart = null;
let cache = [];
console.log = function(...agrs) {
emit('log', {
log: agrs,
})
}
function emit(event, data) {
postMessage({
// event,
data
})
cache = []
}
function postMessage(data) {
window.__uniapp_x_.postMessage(JSON.stringify(data))
};
function stringify(key, value) {
if (typeof value === 'object' && value !== null) {
if (cache.indexOf(value) !== -1) {
return;
}
cache.push(value);
}
return value;
}
function parse(name, callback, options) {
const optionNameReg = /[\w]+\.setOption\(([\w]+\.)?([\w]+)\)/
if (optionNameReg.test(callback)) {
const optionNames = callback.match(optionNameReg)
if (optionNames[1]) {
const _this = optionNames[1].split('.')[0]
window[_this] = {}
window[_this][optionNames[2]] = options
return optionNames[2]
} else {
return null
}
}
return null
}
function init(callback, options, opts = {}, theme = null) {
if (!chart) {
chart = echarts.init(document.getElementById('limeChart'), theme, opts)
if (options) {
chart.setOption(options)
}
}
}
function on(data) {
if (chart && data.length > 0) {
const [type, query] = data
const key = `${type}${JSON.stringify(query??'')}`
if (query) {
chart.on(type, query, (options) => {
const obj = {}
Object.keys(options).forEach(key => {
if (key != 'event') {
obj[key] = options[key]
}
})
emit(key, {
event: key,
options: obj
})
})
} else {
chart.on(type, (options) => {
const obj = {}
Object.keys(options).forEach(key => {
if (key != 'event') {
obj[key] = options[key]
}
})
emit(key, {
event: key,
options: obj
})
})
}
}
}
function setChart(callback, options) {
if (!callback) return
if (chart && callback && options) {
var r = null
const name = parse('r', callback, options)
if (name) this[name] = options
eval(`r = ${callback};`)
if (r) {
r(chart)
}
}
}
function setOption(data) {
if (chart) chart.setOption(data[0], data[1])
}
function showLoading(data) {
if (chart) chart.showLoading(data[0], data[1])
}
function hideLoading() {
if (chart) chart.hideLoading()
}
function clear() {
if (chart) chart.clear()
}
function dispose() {
if (chart) chart.dispose()
}
function resize(size) {
if (chart) chart.resize(size)
}
function canvasToTempFilePath(opt = {}) {
if (chart) {
delete opt.success
const src = chart.getDataURL(opt)
postMessage({
// event: 'file',
file: file
})
}
}
</script>
</body>
</html>