gpt4 book ai didi

javascript - d3scale线性更新和缩放冲突

转载 作者:行者123 更新时间:2023-12-03 02:24:29 25 4
gpt4 key购买 nike

我在 d3 中结合手动更新和缩放功能时遇到问题。

这是一个从较大模块中切出的小演示代码,仅创建线性比例。

https://jsfiddle.net/superkamil/x3v2yc7j/2

class LinearScale {
constructor(element, options) {
this.element = d3.select(element);
this.options = options;

this.scale = this._createScale();
this.axis = this._createAxis();
this.linearscale = this._create();
}

update(options) {
this.options = Object.assign(this.options, options);

this.scale = this._createScale();
this.axis = this._createAxis();

this.linearscale.call(this.axis);
}

_create() {
const scale = this.element
.append('g')
.attr('class', 'linearscale')
.call(this.axis);

this.zoom = d3.zoom().on('zoom', () => this._zoomed());

this.element.append('rect')
.style('visibility', 'hidden')
.style('width', this.options.width)
.style('height', this.options.height)
.attr('pointer-events', 'all')
.call(this.zoom);

return scale;
}

_createScale() {
let range = this.options.width;

this.scale = this.scale || d3.scaleLinear();

this.scale.domain([
this.options.from,
this.options.to
]).range([0, range]);

return this.scale;
}

_createAxis() {
if (this.axis) {
this.axis.scale(this.scale);
return this.axis;
}

return d3.axisBottom(this.scale);
}

_zoomed() {
this.linearscale
.call(this.axis.scale(d3.event.transform.rescaleX(this.scale)));

let domain = this.axis.scale().domain();

this.element.dispatch('zoomed', {
detail: {
from: domain[0],
to: domain[1],
},
});
}
}

const scale = new LinearScale(document.getElementById('axis'), {
from: 0,
to: 600,
width: 600,
height: 100
});

document.getElementById('set').addEventListener('click', () => {
scale.update({
from: 0,
to: 100
});
});
  1. 将 x 轴缩放至 0 - 10000(随机数)
  2. 点击“设置”按钮
  3. X 轴设置范围为 0 - 100
  4. 再次开始缩小

-> 预期:缩放从域 0 - 100 开始

-> 结果:缩放跳回之前的缩放级别 0 - 10000

我知道,d3 正在使用比例副本,并且我正在更新原始比例,但我找不到如何组合它们或如何将缩放级别设置为原始比例的方法。

https://github.com/d3/d3-zoom/blob/master/README.md#transform_rescaleX

谢谢!

enter image description here

最佳答案

您可以重新创建缩放行为,也可以只是重置当前的缩放变换。您应该能够重置每个参数(缩放和平移)或只是重置所有参数。以下示例还触发缩放特定事件,但由于您已经设置了域,因此它不应该是视觉问题。

例如:添加 this.element.select("rect").call(this.zoom.transform, d3.zoomIdentity);在你的更新函数中。

有关 Zoom api 的更多信息,请参阅 https://github.com/d3/d3-zoom/blob/master/README.md#zoom_transform 。我还发现了一个使用过渡动画的示例 https://bl.ocks.org/mbostock/db6b4335bf1662b413e7968910104f0f 。我还更新了 fiddle :

update(options) {

this.options = Object.assign(this.options, options);
this.scale = this._createScale();
this.axis = this._createAxis();

this.linearscale.call(this.axis);
this.element.select("rect").call(this.zoom.transform, d3.zoomIdentity);
}

https://jsfiddle.net/x3v2yc7j/8/

关于javascript - d3scale线性更新和缩放冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49010175/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com