项目场景:
用Echarts画力导向图,节点文字随鼠标缩放而缩放
解决方案:
用原生函数getZr()或_zr()实现,例子如下:
this.nodes=[],//节点数据
this.links=[];//边数据
let fontSize=12;//初始化字体大小
let myForce = echarts.init(document.getElementById('myForce'));
let option={
title:{
show : true,
text:'路径图'
}
},
series: [
{
type: 'graph',
layout: 'force',//力引导布局
symbolSize: 50,
roam: true,//开启鼠标缩放和平移
edgeSymbol: ['circle', 'arrow'],// 边两端的标记类型
edgeSymbolSize: [4, 15],
force: {
repulsion: 1500,//节点之间的距离
edgeLength: [10, 40],
layoutAnimation:true
},
draggable: true,
itemStyle: {
normal: {
color: '#4b565b'
}
},
lineStyle: {
width: 2,
},
edgeLabel: {//关系边的公用线条
normal: {
show: true,
textStyle: {
fontSize: fontSize,
color:'black',
},
formatter: function (x) {
return x.data.relation;
}
}
},
label: { //节点圈里的字体
normal: {
show: true,
position:'bottom',
distance : 15,
fontSize :fontSize,
color:'black'
}
},
data: this.nodes,
links:this.links
}
]
myForce.clear();
myForce.setOption(option,true);
//鼠标点击节点位置不跳动
myForce.on('mouseup', function (params) {
var option = myForce.getOption();
//自己定义位置
option.series[0].data[params.dataIndex].x = params.data.x;
option.series[0].data[params.dataIndex].y = params.data.y;
option.series[0].data[params.dataIndex].fixed = true;
//设置文字
option.series[0].label.fontSize = fontSize;
// option.series[0].label.lineHeight=fontSize * 1.25;
option.series[0].edgeLabel.textStyle.fontSize = fontSize;
myForce.setOption(option);
});
let preZoom = 1;
//设置文字(缩放文字)
myForce.getZr().on("mousewheel", function () {
var option = myForce.getOption();
var zoom = option.series[0].zoom;
if (zoom !== preZoom) {
preZoom = zoom;
fontSize = 12 * zoom;
option.series[0].label.fontSize = fontSize;
option.series[0].label.lineHeight = fontSize * 1.25;
option.series[0].edgeLabel.textStyle.fontSize = fontSize;
myForce.setOption(option);
}
});
window.onresize = function() {
myForce.resize();
}