示例:實現拖拽

這是一個小例子,介紹如何在 Apache EChartsTM 中實現圖形元素的拖拽。從這個例子中,你將看到,如何基於 ECharts API 做出具有豐富互動的圖表。

這個例子主要實現了,拖拽修改曲線上的點,從而改變曲線的形狀。雖然例子簡單,但是基於此可以做出更復雜的應用,例如視覺化地編輯圖表。那麼,就讓我們從這個簡單的例子開始吧。

實現基本拖拽

首先,我們建立一個基本的折線圖

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
    }
  ]
});

因為折線圖的拐點本身不支援拖拽,所以我們使用 ECharts 的圖形元件(graphic component),在每個拐點上,覆蓋一個可拖拽的圓點。

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)
    };
  })
});

在上面的程式碼中,使用了 API convertToPixel,這個 API 可以把資料轉換成“畫素座標”。基於“畫素座標”,我們可以把圖形元素繪製在畫布上。“畫素座標”是指,座標系的原點在畫布的左上角。在語句 myChart.convertToPixel('grid', dataItem) 中,第一個引數 'grid' 表示 dataItem 是在第一個直角座標系(grid)中定義的。

注意: 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
      }
    ]
  });
}

在上面的程式碼中,使用了 API convertFromPixel,它是 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'
  });
}

API dispatchAction 被用來顯示和隱藏 tooltip,其中 showTiphideTip action 被派發。

完整程式碼

完整程式碼如下所示。

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 上編輯此頁

Oviliapissang