echarts折线图实现对label标签拖拽功能
最近需要实现一个前端页面中,对label标签实现拖拽的功能,基本的原理是 对某个点位的相对位置进行计算和定位,功能如下:
代码如下
html部分
html部分
<template>
<div style="height: 100%;overflow: auto">
<div id="myCharts" ref="myCharts" ></div>
</div>
</template>
js部分
<script>
import * as echarts from "echarts";
export default {
data() {
return {
myEchart: null,
option: {
},
echartsParams: null,
showIndex:0,
};
},
mounted() {
this.createEchart();
},
methods: {
createEchart() {
let data = [[10, 20],[30, 40], [50, 60], [60, 70], [60, 60], [56, 66]];
this.myChart = echarts.init(this.$refs.myCharts);
this.option = {
xAxis: {
type: 'value',
},
yAxis: {
type: 'value'
},
series: [
{
type: "line",
data:data,
label: {
show: true,
position: "inside",
fontSize: 0,
width: 150,
offset: [0, 0],
formatter: (params) => {
console.log(params)
if (data.length - 1 == params.dataIndex) {
return '这是一个可移动的公式'
} else {
return ""
}
},
},
labelLine: {
show: false,
lineStyle: {
color: "#707070",
with: 2,
type: "solid",
opacity: 0,
},
},
},
],
};
this.option && this.myChart.setOption(this.option);
let that = this;
this.myChart.on("click", {
seriesType: "line"}, function (params) {
console.log(123)
console.log(params)
if (
that.option.series[params.seriesIndex].labelLine.lineStyle.opacity ==
false
) {
that.option.series[params.seriesIndex].label.fontSize = 12;
that.showIndex += 1;
that.option.series[params.seriesIndex].label.offset = [0, 70];
} else {
that.option.series[params.seriesIndex].label.fontSize = 0;
that.option.series[params.seriesIndex].label.offset = [0, 0];
that.showIndex -= 1;
}
that.option.series[params.seriesIndex].labelLine.lineStyle.opacity =
!that.option.series[params.seriesIndex].labelLine.lineStyle.opacity;
that.myChart.setOption(that.option);
});
this.myChart.on("mousedown", 'series.line', function (params) {
that.echartsParams = params;
document
.getElementById("myCharts")
.addEventListener("mouseup", that.mouseUpEchart);
});
},
mouseUpEchart(e) {
let that = this;
console.log("开始")
console.log(e)
console.log(that.echartsParams.event)
console.log(that.option.series[that.echartsParams.seriesIndex].label.offset)
const initX =
that.echartsParams.event.offsetX -
that.option.series[that.echartsParams.seriesIndex].label.offset[0];
const initY =
that.echartsParams.event.offsetY -
that.option.series[that.echartsParams.seriesIndex].label.offset[1];
that.option.series[that.echartsParams.seriesIndex].label.offset = [
e.offsetX - initX,
e.offsetY - initY,
];
console.log(that.option.series[that.echartsParams.seriesIndex].label.offset)
that.myChart.setOption(that.option);
document
.getElementById("myCharts")
.removeEventListener("mouseup", that.mouseUpEchart);
},
},
};
</script>
样式
#myCharts {
width: 1000px;
height: 500px;
margin: auto;
}
如果感觉有用,记得点个赞哦!您的鼓励是我持续更新的动力,一起努力,一起变更强,加油
end