2

我是 Tradingview 图表库的新手,我想创建响应式图表。

问题是,交易视图图表库需要指定宽度和高度。这是代码。

const chart = LightweightCharts.createChart(e, {
      width: e.offsetWidth,
      height: e.offsetHeight,
      layout: {
        backgroundColor: 'rgb(17, 17, 39)',
        textColor: 'rgba(255, 255, 255, 0.9)',
      },
      grid: {
        vertLines: {
          color: 'rgb(41, 44, 58)',
        },
        horzLines: {
          color: 'rgb(41, 44, 58)',
        },
      },
      crosshair: {
        mode: LightweightCharts.CrosshairMode.Normal,
      },
      priceScale: {
        borderColor: 'rgba(197, 203, 206, 0.8)',
      },
      timeScale: {
        borderColor: 'rgba(197, 203, 206, 0.8)',
      },
    });
4

2 回答 2

3

这是 timocov 评论中的代码,它可以正常工作。放在createChart和之后setData。并将 chartContainer 重命名为您的图表容器 HTML 元素。

  // Make Chart Responsive with screen resize
  new ResizeObserver(entries => {
      if (entries.length === 0 || entries[0].target !== chartContainer) { return; }
      const newRect = entries[0].contentRect;
      chart.applyOptions({ height: newRect.height, width: newRect.width });
    }).observe(chartContainer);
于 2021-12-17T06:15:58.440 回答
1

您需要在包含图表的容器元素上检测调整大小事件,然后使用chart.applyOptions({ width: newWidth, height: newHeight })

有一些库可以检测元素调整大小,我能找到的最好的非 lib 方法是使用ResizeObserverAPI,但看起来它可能还没有集成到所有现代浏览器中。您将使用元素新的高度/宽度设置更新回调函数,并在ResizeObserver

function resize() {
    chart.applyOptions({ width: $('#chartDiv').width(), height: $('#chartDiv').height() })
}

new ResizeObserver(outputsize).observe($('#chartDiv'))
于 2019-09-12T17:55:12.183 回答