<template>
<div>
<!-- #ifdef APP-PLUS-->
<view class="echarts">
<e-charts-vue v-if="options" id="echartsPrice" :height="460" :options="options" />
</view>
<!-- #endif -->
<!-- #ifdef MP-->
<view class="echarts">
<wx-chart-canvas id="lineChart" ref="canvas" class="wx-chart-canvas" canvas-id="wx-chart-canvas" :ec="ec">
</wx-chart-canvas>
</view>
<!-- #endif -->
</div>
</template>
<script>
export default {
data() {
return {
option: '',
ec: {
option: '',
},
options: {}
}
},
onLoad(val) {
this.option = val
this._getEchartDate(val)
},
methods: {
// 获取图表数据
async _getEchartDate(option) {
// let quotationDate = dayjs(this.item.add_time).format('YYYY-MM-DD')
try {
const params = {
id: 1234567
}
const res = await getTrend(params)
if (res.Code === 200) {
this.chartY = res.Data.price || []
this.chartX = res.Data.date || []
this.initLineEcharts(this.chartX, this.chartY)
}
} catch (err) {
console.log(err)
}
},
initChart(canvas, width, height, canvasDpr) {
chart = echarts.init(canvas, null, {
width: width,
height: height,
devicePixelRatio: canvasDpr
})
canvas.setChart(chart)
chart.setOption(this.ec.option)
return chart
},
// 初始化(折线图)
initLineEcharts(chartX, chartY) {
let min = Math.floor(Math.min(...chartY) / 1.05)
let max = Math.ceil(Math.max(...chartY) * 1.05)
let interval = (max - min) / 5;
let chartOptions = {
grid: {
top: 30,
bottom: 32,
left: (this.item?.mainclass_id === 6) ? 68 : 58,
right: 22,
},
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'line',
axis: 'x',
},
label: {
show: true,
},
},
xAxis: {
type: 'category',
show: true,
data: chartX,
nameLocation: 'start',
},
yAxis: {
type: 'value',
name: this.item.unit || '元/吨',
nameLocation: 'end',
nameTextStyle: {
verticalAlign: 'middle',
},
scale: true,
axisLine: {
lineStyle: {
color: '#666',
},
},
splitLine: {
show: true,
lineStyle: {
color: '#e3e3e3',
},
},
min: min,
max: max,
splitNumber: 4,
interval: interval,
},
color: ['#4167a8'],
series: [{
type: 'line',
name: `参考价`,
data: chartY,
showSymbol: false,
lineStyle: {
width: 1,
},
},],
}
// #ifdef APP-PLUS
this.options = chartOptions
// #endif
// #ifdef MP
this.ec.option = chartOptions
this.$nextTick(() => {
this.$refs.canvas.init(this.initChart)
});
// #endif
},
},
}
</script>
<style lang=scss></style>
- 安装echarts@5.2.2
- 微信小程序展示的echarts:index.vue
<template>
<canvas type="2d" v-if="isUseNewCanvas" class="ec-canvas" :canvas-id="canvasId" @init="init" @touchstart="touchStart"
@touchmove="touchMove" @touchend="touchEnd">
</canvas>
<canvas v-else class="ec-canvas" :canvas-id="canvasId" @init="init" @touchstart="touchStart" @touchmove="touchMove"
@touchend="touchEnd">
</canvas>
</template>
<script>
import WxCanvas from "./wx-canvas";
import * as echarts from "echarts";
let ctx;
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 default {
props: {
canvasId: {
type: String,
default: () => {
return "ec-canvas";
}
},
ec: {
type: Object
},
forceUseOldCanvas: {
type: Boolean,
value: false
}
},
data() {
return {
$curChart: {},
toHandleList: [],
isUseNewCanvas: true
};
},
watch: {
"ec.option": {
deep: true,
handler(val, oldVal) {
this.setOption(val);
}
}
},
onReady: function () {
if (!this.ec) {
console.warn(
'组件需绑定 ec 变量,例:<ec-canvas id="mychart-dom-bar" ' +
'canvas-id="mychart-bar" ec="{{ ec }}"></ec-canvas>'
);
return;
}
if (!this.ec.lazyLoad) {
this.init();
}
},
methods: {
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]);
const num2 = parseInt(v2[i]);
if (num1 > num2) {
return 1;
} else if (num1 < num2) {
return -1;
}
}
return 0;
},
init(callback) {
const version = wx.getSystemInfoSync().SDKVersion;
let canUseNewCanvas = this.compareVersion(version, "2.9.0") >= 0;
if (this.forceUseOldCanvas) {
if (canUseNewCanvas) console.warn("开发者强制使用旧canvas,建议关闭");
canUseNewCanvas = false;
}
this.isUseNewCanvas = canUseNewCanvas && !this.forceUseOldCanvas;
if (this.isUseNewCanvas) {
console.log('微信基础库版本大于2.9.0,开始使用<canvas type="2d"/>');
// 2.9.0 可以使用 <canvas type="2d"></canvas>
this.initByNewWay(callback);
} else {
const isValid = this.compareVersion(version, "1.9.91") >= 0;
if (!isValid) {
console.error(
"微信基础库版本过低,需大于等于 1.9.91。" +
"参见:https://github.com/ecomfe/echarts-for-weixin" +
"#%E5%BE%AE%E4%BF%A1%E7%89%88%E6%9C%AC%E8%A6%81%E6%B1%82"
);
return;
} else {
console.warn(
"建议将微信基础库调整大于等于2.9.0版本。升级后绘图将有更好性能"
);
this.initByOldWay(callback);
}
}
},
initByOldWay(callback) {
// 1.9.91 <= version < 2.9.0:原来的方式初始化
ctx = wx.createCanvasContext(this.canvasId, this);
const canvas = new WxCanvas(ctx, this.canvasId, false);
const that = this
echarts.setCanvasCreator(() => {
return canvas;
});
// const canvasDpr = wx.getSystemInfoSync().pixelRatio // 微信旧的canvas不能传入dpr
const canvasDpr = 1;
var query = wx.createSelectorQuery().in(this);
query
.select(".ec-canvas")
.boundingClientRect(res => {
if (typeof callback === "function") {
that.$curChart = callback(canvas, res.width, res.height, canvasDpr);
} else if (that.ec) {
that.initChart(canvas, res.width, res.height, canvasDpr)
} else {
that.triggerEvent("init", {
canvas: canvas,
width: res.width,
height: res.height,
devicePixelRatio: canvasDpr // 增加了dpr,可方便外面echarts.init
});
}
})
.exec();
},
initByNewWay(callback) {
const that = this
// version >= 2.9.0:使用新的方式初始化
const query = wx.createSelectorQuery().in(this);
query
.select(".ec-canvas")
.fields({
node: true,
size: true
})
.exec(res => {
const canvasNode = res[0].node;
const canvasDpr = wx.getSystemInfoSync().pixelRatio;
const canvasWidth = res[0].width;
const canvasHeight = res[0].height;
const ctx = canvasNode.getContext("2d");
const canvas = new WxCanvas(ctx, that.canvasId, true, canvasNode);
echarts.setCanvasCreator(() => {
return canvas;
});
if (typeof callback === "function") {
that.$curChart = callback(
canvas,
canvasWidth,
canvasHeight,
canvasDpr
);
} else if (that.ec) {
that.initChart(canvas, canvasWidth, canvasHeight, canvasDpr)
} else {
that.triggerEvent("init", {
canvas: canvas,
width: canvasWidth,
height: canvasHeight,
devicePixelRatio: canvasDpr
});
}
});
},
setOption(val) {
if (!this.$curChart || !this.$curChart.setOption) {
this.toHandleList.push(val);
} else {
this.$curChart.setOption(val);
}
},
canvasToTempFilePath(opt) {
if (this.isUseNewCanvas) {
// 新版
const query = wx.createSelectorQuery().in(this);
query
.select(".ec-canvas")
.fields({
node: true,
size: true
})
.exec(res => {
const canvasNode = res[0].node;
opt.canvas = canvasNode;
wx.canvasToTempFilePath(opt);
});
} else {
// 旧的
if (!opt.canvasId) {
opt.canvasId = this.canvasId;
}
ctx.draw(true, () => {
wx.canvasToTempFilePath(opt, this);
});
}
},
touchStart(e) {
if (this.ec.stopTouchEvent) {
e.preventDefault();
e.stopPropagation();
return;
}
this.$emit("touchstart", e);
if (this.$curChart && e.touches.length > 0) {
var touch = e.touches[0];
var handler = this.$curChart.getZr().handler;
if (handler) {
handler.dispatch("mousedown", {
zrX: touch.x,
zrY: touch.y
});
handler.dispatch("mousemove", {
zrX: touch.x,
zrY: touch.y
});
handler.processGesture(wrapTouch(e), "start");
}
}
},
touchMove(e) {
if (this.ec.stopTouchEvent) {
e.preventDefault();
e.stopPropagation();
return;
}
this.$emit("touchmove", e);
if (this.$curChart && e.touches.length > 0) {
var touch = e.touches[0];
var handler = this.$curChart.getZr().handler;
if (handler) {
handler.dispatch("mousemove", {
zrX: touch.x,
zrY: touch.y
});
handler.processGesture(wrapTouch(e), "change");
}
}
},
touchEnd(e) {
if (this.ec.stopTouchEvent) {
e.preventDefault();
e.stopPropagation();
return;
}
this.$emit("touchend", e);
if (this.$curChart) {
const touch = e.changedTouches ? e.changedTouches[0] : {};
var handler = this.$curChart.getZr().handler;
if (handler) {
handler.dispatch("mouseup", {
zrX: touch.x,
zrY: touch.y
});
handler.dispatch("click", {
zrX: touch.x,
zrY: touch.y
});
handler.processGesture(wrapTouch(e), "end");
}
}
},
initChart(canvas, width, height, canvasDpr) {
this.$curChart = echarts.init(canvas, null, {
width: width,
height: height,
devicePixelRatio: canvasDpr
});
canvas.setChart(this.$curChart);
this.$curChart.setOption(this.ec.option);
}
}
};
</script>
<style lang="scss">
.ec-canvas {
width: 100%;
height: 100%;
display: block;
}
</style>
export default class WxCanvas {
constructor(ctx, canvasId, isNew, canvasNode) {
this.ctx = ctx;
this.canvasId = canvasId;
this.chart = null;
this.isNew = isNew
if (isNew) {
this.canvasNode = canvasNode;
} else {
this._initStyle(ctx);
}
// this._initCanvas(zrender, ctx);
this._initEvent();
}
getContext(contextType) {
if (contextType === '2d') {
return this.ctx;
}
}
// canvasToTempFilePath(opt) {
// if (!opt.canvasId) {
// opt.canvasId = this.canvasId;
// }
// return wx.canvasToTempFilePath(opt, this);
// }
setChart(chart) {
this.chart = chart;
}
attachEvent() {
// noop
}
detachEvent() {
// noop
}
_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);
});
}
_initStyle(ctx) {
var 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 = () => {
return 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.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) {
if (this.canvasNode) this.canvasNode.width = w
}
set height(h) {
if (this.canvasNode) this.canvasNode.height = h
}
get width() {
if (this.canvasNode)
return this.canvasNode.width
return 0
}
get height() {
if (this.canvasNode)
return this.canvasNode.height
return 0
}
}
<template>
<!-- #ifdef APP-PLUS || H5 -->
<view @click="echarts && echarts.onClick" :prop="option" :change:prop="echarts && echarts.updateEcharts" :id="id"
class="echarts" :style="{
width: typeof width === 'number' ? width + 'rpx' : width,
height: height + 'rpx'
}">
</view>
<!-- #endif -->
</template>
<script>
export default {
props: {
options: {
type: Object,
default: () => ({}),
},
width: {
type: [Number, String],
default: () => '100%',
},
height: {
type: Number,
default: 200,
},
// 动态传id
id: {
type: String,
dafault: 'echarts',
},
},
watch: {
options: {
handler(newValue, oldValue) {
this.option = newValue
},
immediate: true,
deep: true, // 深度监听
},
},
methods: {
onViewClick(value) {
console.log('service 层方法', value)
},
},
}
</script>
<script module="echarts" lang="renderjs">
let myChart
export default {
mounted() {
if (typeof window.echarts === 'function') {
this.initEcharts()
} else {
// 动态引入较大类库避免影响页面展示
const script = document.createElement('script')
// view 层的页面运行在 www 根目录,其相对路径相对于 www 计算
script.src = 'https://css.ccement.com/js/cdn/uniapp/echarts.min.js'
script.onload = this.initEcharts.bind(this)
document.head.appendChild(script)
}
},
methods: {
initEcharts() {
myChart = echarts.init(document.getElementById(this.id),null,{renderer:'svg'})
if(this.id !== 'echartsPrice'){
this.option.xAxis.axisLabel.formatter = function formatter(value) {
var date = new Date(value)
var year = date.getFullYear()
var month = date.getMonth() + 1
var day = date.getDate()
return year + '-' + (month > 9 ? month : '0' + month) + '-' + (day > 9 ? day : '0' + day)
}
this.option.xAxis.min = (value) => {
return value.min - 30 * 24 * 60 * 60 * 1000
}
this.option.xAxis.max = (value) => {
return value.max + 30 * 24 * 60 * 60 * 1000
}
this.option.yAxis.min = (value) => {
return value.min - 10
}
this.option.yAxis.max = (value) => {
return value.max + 10
}
}else{
// 价格详情过来的
this.option.yAxis.min = (value) => {
return Math.floor(value.min / 1.05)
}
this.option.tooltip.formatter = (params)=> {
return `${params[0]?.name}<br/>参考价:${params[0].value}`
}
}
console.log(this.option);
// 观测更新的数据在 view 层可以直接访问到
myChart && myChart.setOption(this.option)
},
updateEcharts(newValue, oldValue, ownerInstance, instance) {
// 监听 service 层数据变更
myChart && myChart.setOption(newValue)
},
onClick(event, ownerInstance) {
// 调用 service 层的方法
ownerInstance.callMethod('onViewClick', {
test: 'test'
})
}
}
}
</script>
<style>
.echarts {
width: 100%;
height: 300px;
}
</style>