一个例子:实现拖拽

这是一个简单的示例,介绍了如何使用 Apache EChartsTM 实现图形元素的拖拽。通过这个例子,我们将看到如何基于 echarts API 构建具有丰富交互性的应用。

该示例主要实现的是:通过拖拽曲线上的点来修改曲线。虽然这是一个简单的例子,但我们可以在此基础上做更多事情,比如可视化地编辑图表。让我们从这个简单的例子开始吧。

实现基础拖拽

首先,我们创建一个基础的折线图(line series)

var symbolSize = 20;
var data = [
  [15, 0],
  [-50, 10],
  [-56.5, 20],
  [-46.5, 30],
  [-22.1, 40]
];

myChart.setOption({
  xAxis: {
    min: -100,
    max: 80,
    type: 'value',
    axisLine: { onZero: false }
  },
  yAxis: {
    min: -30,
    max: 60,
    type: 'value',
    axisLine: { onZero: false }
  },
  series: [
    {
      id: 'a',
      type: 'line',
      smooth: true,
      // Set a big symbolSize for dragging convenience.
      symbolSize: symbolSize,
      data: data
    }
  ]
});

由于折线图中的标记(symbol)默认不支持拖拽,我们利用 graphic 组件,在每个标记的位置分别添加可拖拽的圆形元素,从而实现拖拽功能。

myChart.setOption({
  // Declare a graphic component, which contains some graphic elements
  // with the type of 'circle'.
  // Here we have used the method `echarts.util.map`, which has the same
  // behavior as Array.prototype.map, and is compatible with ES5-.
  graphic: echarts.util.map(data, function(dataItem, dataIndex) {
    return {
      // 'circle' means this graphic element is a shape of circle.
      type: 'circle',

      shape: {
        // The radius of the circle.
        r: symbolSize / 2
      },
      // Transform is used to located the circle. position:
      // [x, y] means translate the circle to the position [x, y].
      // The API `convertToPixel` is used to get the position of
      // the circle, which will introduced later.
      position: myChart.convertToPixel('grid', dataItem),

      // Make the circle invisible (but mouse event works as normal).
      invisible: true,
      // Make the circle draggable.
      draggable: true,
      // Give a big z value, which makes the circle cover the symbol
      // in line series.
      z: 100,
      // This is the event handler of dragging, which will be triggered
      // repeatly while dragging. See more details below.
      // A util method `echarts.util.curry` is used here to generate a
      // new function the same as `onPointDragging`, except that the
      // first parameter is fixed to be the `dataIndex` here.
      ondrag: echarts.util.curry(onPointDragging, dataIndex)
    };
  })
});

在上述代码中,使用了 convertToPixel API 将数据转换为“像素坐标”,从而使每个图形元素都能在画布上渲染。“像素坐标”是指相对于画布左上角的像素位置。在 myChart.convertToPixel('grid', dataItem) 语句中,第一个参数 'grid' 表示 dataItem 应该在第一个 直角坐标系(grid component) 中进行转换。

注意: convertToPixel 不应在第一次调用 setOption 之前调用。也就是说,它只能在坐标系(grid/polar/...)初始化之后使用。

现在点已经变得可拖拽了。接下来我们将为这些点绑定拖拽事件监听器。

// This function will be called repeatly while dragging.
// The mission of this function is to update `series.data` based on
// the new points updated by dragging, and to re-render the line
// series based on the new data, by which the graphic elements of the
// line series can be synchronized with dragging.
function onPointDragging(dataIndex) {
  // Here the `data` is declared in the code block in the beginning
  // of this article. The `this` refers to the dragged circle.
  // `this.position` is the current position of the circle.
  data[dataIndex] = myChart.convertFromPixel('grid', this.position);
  // Re-render the chart based on the updated `data`.
  myChart.setOption({
    series: [
      {
        id: 'a',
        data: data
      }
    ]
  });
}

上述代码使用了 convertFromPixel API,它是 convertToPixel 的逆过程。myChart.convertFromPixel('grid', this.position) 将像素坐标转换为 直角坐标系(grid) 中的数据项。

最后,添加这些代码使图形元素能够响应画布大小的变化。

window.addEventListener('resize', function() {
  // Re-calculate the position of each circle and update chart using `setOption`.
  myChart.setOption({
    graphic: echarts.util.map(data, function(item, dataIndex) {
      return {
        position: myChart.convertToPixel('grid', item)
      };
    })
  });
});

添加提示框(tooltip)组件

至此,第一部分已经实现了基础功能。如果我们希望在拖拽时实时显示数据,可以使用 tooltip 组件。然而,tooltip 组件有其默认的“显示/隐藏规则”,并不适用于当前场景。因此,我们需要为我们的案例自定义“显示/隐藏规则”。

将这些代码片段添加到上述代码块中

myChart.setOption({
  // ...,
  tooltip: {
    // Means disable default "show/hide rule".
    triggerOn: 'none',
    formatter: function(params) {
      return (
        'X: ' +
        params.data[0].toFixed(2) +
        '<br>Y: ' +
        params.data[1].toFixed(2)
      );
    }
  }
});
myChart.setOption({
  graphic: data.map(function(item, dataIndex) {
    return {
      type: 'circle',
      // ...,
      // Customize "show/hide rule", show when mouse over, hide when mouse out.
      onmousemove: echarts.util.curry(showTooltip, dataIndex),
      onmouseout: echarts.util.curry(hideTooltip, dataIndex)
    };
  })
});

function showTooltip(dataIndex) {
  myChart.dispatchAction({
    type: 'showTip',
    seriesIndex: 0,
    dataIndex: dataIndex
  });
}

function hideTooltip(dataIndex) {
  myChart.dispatchAction({
    type: 'hideTip'
  });
}

使用 dispatchAction API 来显示/隐藏提示框内容,其中派发了 showTiphideTip 动作。

完整代码

完整代码如下所示

import echarts from 'echarts';

var symbolSize = 20;
var data = [
  [15, 0],
  [-50, 10],
  [-56.5, 20],
  [-46.5, 30],
  [-22.1, 40]
];
var myChart = echarts.init(document.getElementById('main'));
myChart.setOption({
  tooltip: {
    triggerOn: 'none',
    formatter: function(params) {
      return (
        'X: ' +
        params.data[0].toFixed(2) +
        '<br />Y: ' +
        params.data[1].toFixed(2)
      );
    }
  },
  xAxis: { min: -100, max: 80, type: 'value', axisLine: { onZero: false } },
  yAxis: { min: -30, max: 60, type: 'value', axisLine: { onZero: false } },
  series: [
    { id: 'a', type: 'line', smooth: true, symbolSize: symbolSize, data: data }
  ]
});
myChart.setOption({
  graphic: echarts.util.map(data, function(item, dataIndex) {
    return {
      type: 'circle',
      position: myChart.convertToPixel('grid', item),
      shape: { r: symbolSize / 2 },
      invisible: true,
      draggable: true,
      ondrag: echarts.util.curry(onPointDragging, dataIndex),
      onmousemove: echarts.util.curry(showTooltip, dataIndex),
      onmouseout: echarts.util.curry(hideTooltip, dataIndex),
      z: 100
    };
  })
});
window.addEventListener('resize', function() {
  myChart.setOption({
    graphic: echarts.util.map(data, function(item, dataIndex) {
      return { position: myChart.convertToPixel('grid', item) };
    })
  });
});
function showTooltip(dataIndex) {
  myChart.dispatchAction({
    type: 'showTip',
    seriesIndex: 0,
    dataIndex: dataIndex
  });
}
function hideTooltip(dataIndex) {
  myChart.dispatchAction({ type: 'hideTip' });
}
function onPointDragging(dataIndex, dx, dy) {
  data[dataIndex] = myChart.convertFromPixel('grid', this.position);
  myChart.setOption({
    series: [
      {
        id: 'a',
        data: data
      }
    ]
  });
}

利用上面介绍的知识,还可以实现更多功能。例如,可以添加 dataZoom 组件 来配合直角坐标系,或者在坐标系上制作一个画板。发挥你的想象力吧~

贡献者 在 GitHub 上编辑此页

Ovilia Oviliapissang pissang