h5中echarts图表,增加双指缩放功能,支持区域缩放

发布于:2024-05-01 ⋅ 阅读:(51) ⋅ 点赞:(0)

起因:在h5的echarts中,数据量过多,增加了dataZoom,但是折线图依然不美观。产品希望通过双指移动事件,显示折线图的数据。

解决:

1、echarts保留dataZoom,但是将height设置为0,start是0,end是100。

2、使用检测触摸手势的js库:hammer.js,检测手势。

3、监听手势,获得双指移动的缩放比例,更新echarts 的 dataZoom 范围。

index.html
<script src="https://cdn.bootcdn.net/ajax/libs/hammer.js/2.0.8/hammer.min.js"></script>
<script setup>
const setOptions = () => {
  if (props.isZoom) {
    option.dataZoom = [
      {
        height: 0,
        start: 0,
        end: 100,
        showDataShadow: true, //组件中显示数据阴影
        showDetail: false, //拖拽时候显示详细数值信息
        borderColor: "transparent", //组件边框颜色
        dataBackground: {
          lineStyle: {
            color: "#00b48c",
            type: "solid",
            join: "round",
            opacity: 1,
          },
          areaStyle: {
            color: "rgba(0, 214, 174, 0.49)",
          },
        }, //数据阴影的样式
        fillerColor: "transparent", //选中范围的填充颜色
        selectedDataBackground: {
          lineStyle: {
            color: "#00b48c",
            type: "solid",
            join: "round",
            opacity: 1,
          },
          areaStyle: {
            color: "rgba(0, 214, 174, 0.49)",
          },
        }, //选中部分数据阴影的样式
        handleStyle: {
          borderColor: "#00b48c",
          color: "#ffffff",
        }, //两侧缩放手柄的样式配置
        moveHandleSize: 0,
        moveHandleStyle: {
          color: "#00d4b7",
          opacity: 0.49,
        }, //移动手柄的样式配置
        emphasis: {
          handleStyle: {
            borderColor: "#00b48c",
          },
          moveHandleStyle: {
            color: "#00d4b7",
            opacity: 0.49,
          },
        },
      },
    ];
  }
  // 使用指定的配置项和数据显示图表
  myChart.setOption(option);
  onTouch();
}

const onTouch = () => {
  const hammer = new Hammer(main.value);
  hammer.get("pinch").set({ enable: true });
  hammer.on("pinch", (event) => {
    const scale = event.scale; // 获取缩放比例
    if (scale <= 0.5) return //缩放比例不足0.5,不调整范围

    // 根据缩放比例调整 dataZoom 的范围
    const start = Math.max(0, 100 - scale * 100); // 计算起始位置
    const end = Math.min(100, scale * 100); // 计算结束位置

    // 更新 echarts 的 dataZoom 范围
    myChart.dispatchAction({
      type: "dataZoom",
      dataZoomIndex: 0, // 指定dataZoom组件的索引,如果有多个dataZoom组件可以根据实际情况设置
      start, // 设置dataZoom的起始位置
      end, // 设置dataZoom的结束位置
    });
  });
};
</script>