Javascript 如何创建响应性Tradingview轻型图表?
我是Tradingview图表库的新手,我想创建一个响应性好的图表 问题是,交易视图图表库需要指定宽度和高度。这是代码Javascript 如何创建响应性Tradingview轻型图表?,javascript,tradingview-api,lightweight-charts,Javascript,Tradingview Api,Lightweight Charts,我是Tradingview图表库的新手,我想创建一个响应性好的图表 问题是,交易视图图表库需要指定宽度和高度。这是代码 const chart = LightweightCharts.createChart(e, { width: e.offsetWidth, height: e.offsetHeight, layout: { backgroundColor: 'rgb(17, 17, 39)', textColor: 'rgb
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)',
},
});
您需要在包含图表的容器元素上检测到调整大小事件,然后使用
chart.applyOptions({width:newWidth,height:newHeight})更新图表维度
有一些库可以检测元素的大小,我能找到的最好的非库方法是使用ResizeObserver
API,但看起来它可能还没有集成到所有现代浏览器中。您可以使用元素new height/width设置更新回调函数,并在ResizeObserver
中使用该函数:
function resize() {
chart.applyOptions({ width: $('#chartDiv').width(), height: $('#chartDiv').height() })
}
new ResizeObserver(outputsize).observe($('#chartDiv'))
如果使用ResizeObserver,您甚至不需要测量容器的高度:``新ResizeObserver(entries=>{if(entries.length==0 | | | entries[0]。target!==container){return;}const newRect=entries[0]。contentRect;chart.applyOptions({height:newRect.height,width:newRect.width})})。观察(容器)```