G2坐标轴文字过长时添加省略号,悬浮显示全部

778 阅读1分钟

G2坐标轴文字过长时添加省略号,悬浮显示全部

思路:使用G2的事件捕捉坐标轴文字的悬浮事件,然后动态添加dom显示全部文字

// 格式化文字,超过长度添加省略号
this.chart.axis('name', {
  tickLine: null,
  label: {
    offset:4,//距离基线的距离
    autoRotate: false,//关闭默认旋转
    autoEllipsis:true,//是否自动省略
    autoHide: false, // 取消自动隐藏label
    rotate:Math.PI*-0.25,//旋转角度
    style:{
      fill:"#666",
      textBaseline:"top",//自定义label旋转时要设置 否则会以文本为中心旋转会和柱状图重叠
      textAlign:"right",//文字对齐方式,不旋转一般是center
    },
    formatter(text) {
      // 字符太长添加省略号
      return text.length > 4 ? `${text.slice(0, 4)}...` : text;
    },
    rotate: (Math.PI / 180) * -45,
    style: {
      fill: '#666',
      fontSize: 11,
      textAlign: 'right',
    },
  },
});

// 捕捉axis-label的mouseenter事件创建DOM
chart.on('axis-label:mouseenter', (ev) => {
  // 判断是否创建过div框,如果创建过就不再创建了
  const id = document.getElementById('extension');
  if (!id) {
    const div = document.createElement("div");
    div.id = "extension";
    div.style.stysplay = "none";
   
   document.body.appendChild(div);
  }
  
      id.style.position = 'absolute';
      id.style.color = '#333';
      id.style.background = '#fff';
      id.style.boxShadow = '#aeaeae 0 0 10px';
      id.style.fontSize = '12px';
      id.style.padding = '5px';
      id.style.display = 'inline';
      id.style.borderRadius = '3px';
      id.style.zIndex = '100';
      id.innerHTML = ev.target.cfg.delegateObject.item.name;
const idNode = document.getElementById("chiartId");
 idNode.mousemove-function(event) {
    const xx = event.pageX - 30;
    const yy = event.pageY + 20;
    id.style.top = yy +'px';
   id.style.left = xx +'px';
  };
});
// 捕捉axis-mouseleave隐藏DOM
chart.on('axis-label:mouseleave', (ev) => {
   const id = document.getElementById('extension');
 id.style.stysplay = "none";
});