d3复位范围后保持秤/转换 [英] d3 Preserve scale/translate after resetting range

查看:101
本文介绍了d3复位范围后保持秤/转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个< svg> 谁的宽度是它的容器的100%。当容器调整大小时,我更新线性 xScale.range()来表示< svg> 。显然,我需要将范围重新应用到我的缩放行为,如 zoom.x()文档


如果以编程方式修改标尺的域或范围,则应重新调用此函数。设置x-scale还会将比例重置为1,并将其转换为[0,0]。


c $ c> scale 和 translate 是我有问题的地方。如果我之前放大了调整大小,我调用 zoom.x(xScale),现在d3认为图表的比例是1和translate是0,0因此,我不能缩放

解决方案



/ div>

看起来最好的策略是缓存缩放和翻译值,重置,然后重新应用。对于记录,这个代码(在我的resize处理程序中)大致显示我的解决方案:

  //缓存标度
var cacheScale = zoom.scale();

//缓存翻译
var cacheTranslate = zoom.translate();

//缓存将值转换为百分比/全宽比
var cacheTranslatePerc = zoom.translate()。map(function(v,i,a)
{
return(v * -1)/ getFullWidth();
});

//手动重置缩放
zoom.scale(1).translate([0,0]);

//根据调整过的容器尺寸更新范围值
xScale.range([0,myResizedContainerWidth]);

//将更新的xScale应用于缩放
zoom.x(xScale);

//将缩放恢复为缓存值
zoom.scale(cacheScale);

//根据缓存的百分比覆盖cacheTranslate的x值
cacheTranslate [0] = - (getFullWidth()* cacheTranslatePerc [0]);

//最后应用更新的翻译
zoom.translate(cacheTranslate);


function getFullWidth()
{
return xScale.range()[1] * zoom.scale();
}


I have an <svg> who's width is 100% of it's container. When the container is resized, I update the linear xScale.range() to represent the new resized width of the <svg>. Apparently, I then need to reapply the range to my zoom behaviour as outlined in the zoom.x() documentation:

If the scale's domain or range is modified programmatically, this function should be called again. Setting the x-scale also resets the scale to 1 and the translate to [0, 0].

The resetting of the scale and translate is where I have a problem. If I have previously zoomed in before resizing, I call zoom.x( xScale ) and now d3 thinks the chart's scale is 1 and translate is 0,0 therefore, I cannot zoom out or pan.

Is my approach to the way I handle the resize incorrect?

解决方案

It looks like the best strategy is to cache the scale and translate values, reset, then reapply. For the record, this code (within my resize handler) roughly shows my solution:

// Cache scale
var cacheScale = zoom.scale();

// Cache translate
var cacheTranslate = zoom.translate();

// Cache translate values as percentages/ratio of the full width
var cacheTranslatePerc = zoom.translate().map( function( v, i, a )
{
  return (v * -1) / getFullWidth();
} );

// Manually reset the zoom
zoom.scale( 1 ).translate( [0, 0] );

// Update range values based on resized container dimensions
xScale.range( [0, myResizedContainerWidth] );

// Apply the updated xScale to the zoom
zoom.x( xScale );

// Revert the scale back to our cached value
zoom.scale( cacheScale );

// Overwrite the x value of cacheTranslate based on our cached percentage
cacheTranslate[0] = -(getFullWidth() * cacheTranslatePerc[0]);

// Finally apply the updated translate
zoom.translate( cacheTranslate );


function getFullWidth()
{
  return xScale.range()[1] * zoom.scale();
}

这篇关于d3复位范围后保持秤/转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆