Commit f9fa3c41 authored by Jenny's avatar Jenny

feat: uni-ec-canvas

parent b39cfc25
unpackage
node_modules
uview-ui
components/uni-ec-canvas/echarts
\ No newline at end of file
const baseUrl = 'https://api.charleskeith.cn/api' // 请求的本域名
const reportUrl = 'http://192.168.138.55:8081/api'
const install = (Vue, vm) => {
/*************** 认证 API *****************/
// 登录
let quickLogin = params => vm.$u.post('/report/user/quickLogin', params)
let quickLogin = params => vm.$u.post(`${baseUrl}/report/user/quickLogin`, params)
// 报表列表
const getReportList = params => vm.$u.get(`${reportUrl}/report/chart/getList`, params)
// 数据集
const dataSetPreview = params => vm.$u.post(`${reportUrl}/report/dataset/preview`, params)
vm.$u.api = {
quickLogin
quickLogin,
getReportList,
dataSetPreview
}
}
......
const install = (Vue, vm) => {
Vue.prototype.$u.http.setConfig({
baseUrl: 'https://api.charleskeith.cn/api', // 请求的本域名
// baseUrl: 'https://api.charleskeith.cn/api', // 请求的本域名
showLoading: true, // 是否显示请求中的loading
loadingText: '努力加载中。。。', // 请求loading中的文字提示
loadingTime: 300, // 在此时间内,请求还没回来的话,就显示加载中动画,单位ms
loadingMask: true, // 展示loading的时候,是否给一个透明的蒙层,防止触摸穿透
originalData: true, // 是否在拦截器中返回服务端的原始数据
// 配置请求头信息
header: {
"Content-Type": "application/json"
},
})
/**
......@@ -22,7 +26,7 @@ const install = (Vue, vm) => {
Vue.prototype.$u.http.interceptor.response = (res) => {
const { statusCode, data } = res
if(statusCode < 400) {
return data
return res
} else if(statusCode == 400) {
vm.$u.toast(data.message)
return false
......
<template>
<view>
<uni-ec-canvas
class="uni-ec-canvas"
id="line-chart"
ref="canvas"
canvas-id="lazy-load-chart"
:ec="ec"
></uni-ec-canvas>
</view>
</template>
<script>
import uniEcCanvas from '@/components/uni-ec-canvas/uni-ec-canvas'
import * as echarts from '@/components/uni-ec-canvas/echarts'
import echartElementData from '@/mixins/echartElementData.js'
let chart = null
export default {
mixins: [echartElementData],
data () {
return {
ec: {
lazyLoad:true
}
}
},
onReady () {
},
components: {
uniEcCanvas
},
methods: {
initChart() {
this.$nextTick(() => {
this.$refs['canvas'].init((canvas, width, height, canvasDpr) => {
chart = echarts.init(canvas, null, {
width: width,
height: height,
devicePixelRatio: canvasDpr
})
canvas.setChart(chart)
const { dataList: { categories, series } } = this.elementData
const options = {
...this.elementInfo.option,
color: ['#00f2f1', '#ed3f35', '#1089E7', "#F8B448", "#8B78F6",'#8cd8ff', '#f0ad54','#ffffff', '#000000'],
tooltip: {},
xAxis: {
...this.elementInfo.option.xAxis,
data: categories
},
series: this.dealSeriesData(series)
}
chart.setOption(options)
return chart
})
})
},
/**
* 处理数据
*/
dealSeriesData (data) {
if(!data) return
const newData = data.map(item => {
const config = {
type: 'line',
...this.elementInfo.option.line,
label: {
...this.elementInfo.option.dataset,
formatter: val => {
return converFunction(this.elementInfo.option.dataset.formatter, val)
}
}
}
return { ...item, ...config }
})
return newData
}
}
}
</script>
<style scoped>
.uni-ec-canvas{
width: 750rpx;
height: 750rpx;
display:block;
}
</style>
This source diff could not be displayed because it is too large. You can view the blob instead.
<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
}
}
import { converFunction } from '@/utils/common.js'
export default {
data() {
return {
elementData: {},
timer: null
}
},
props: {
elementInfo: {
type: Object,
required: true
}
},
methods: {
/**
* 静态数据
*/
handleStaticData(value) {
this.elementData = JSON.parse(JSON.stringify({...value}))
this.initChart()
},
/**
* 动态数据
*/
async handleDynamicData (value) {
let { dataUrl, dataMethod, dataFormatter, dataProcessing } = { ...value }
if (value.queryFormatter) dataFormatter = {...dataFormatter, ...value.queryFormatter}
let res = await this.$u[dataMethod.toLowerCase()](dataUrl, dataFormatter)
if (dataProcessing) {
this.elementData.dataList = converFunction(dataProcessing, res.data)
} else {
this.elementData.dataList = JSON.parse(JSON.stringify(res.data.Result))
}
this.initChart()
},
/**
* 全局数据
*/
handlePublicData (value) {
},
/**
* 配置数据 - 数据集
*/
async handleDataSet (value) {
const { dataSetInfo } = value
let res = await this.$u.api.dataSetPreview(dataSetInfo)
const { Status, Msg } = res.data;
if (Status == "true") {
if(dataSetInfo.script) {
this.elementData.dataList = converFunction(dataSetInfo.script, res.data.Result)
} else {
this.elementData.dataList = res.data.Result
}
} else {
this.$u.toast(Msg)
}
},
clearTimer() {
clearInterval(this.timer)
this.timer = null
}
},
deactivated() {
this.clearTimer()
},
beforeDestroy() {
this.clearTimer()
},
watch: {
'elementInfo.data': {
handler(newVal) {
if (newVal.dataType === 'static') {
this.handleStaticData(newVal)
}
else if (newVal.dataType === 'dynamic') {
this.handleDynamicData(newVal)
if (newVal.dataPolling) {
this.timer = setInterval(() => {
this.handleDynamicData(newVal)
}, newVal.dataPollingInterval * 1000)
} else {
clearInterval(this.timer)
}
}
else if (newVal.dataType === 'public') {
this.handlePublicData(newVal)
}
else if (newVal.dataType === 'dataSet') {
this.handleDataSet(newVal)
if (newVal.dataPolling) {
this.timer = setInterval(() => {
this.handleDataSet(newVal)
}, newVal.dataPollingInterval * 1000)
} else {
clearInterval(this.timer)
}
}
},
immediate: true,
deep: true
}
}
}
<template>
<view>
首页
<view
class="canvas"
:style="{
backgroundColor: reportInfo.backgroundColor,
backgroundImage: `url(${reportInfo.backgroundImage})`
}"
>
<view v-for="element in reportData" :key="item.id">
<NormalLine v-if="element.type == 'NormalLine'" :elementInfo="element"></NormalLine>
</view>
</view>
</template>
......@@ -8,14 +16,23 @@
export default {
data() {
return {
reportInfo: {},
reportData: []
}
},
async onLoad() {
this.getReportList()
},
methods: {
async getReportList() {
let res = await this.$u.api.getReportList({id: '613ee9e9ce776abde5455495'})
console.log()
const { Status, Result } = res.data
if (Status === 'true') {
this.reportInfo = Result.info
this.reportData = Result.list
}
}
},
onReachBottom() {
......@@ -24,4 +41,13 @@
</script>
<style lang="scss" scoped>
.canvas {
position: relative;
height: 100%;
user-select: none;
overflow: auto;
background-repeat: no-repeat;
background-size: cover;
background-position: center;
}
</style>
/**
* 数据转换
*/
export const converFunction = (func, data) => {
if(!func) return
return Function('"use strict";return (' + func + ')')()(data);
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment