[英]Update zoom state in d3 v4 after manually setting translation and scale
這可能已經被問過很多次了,但是作為d3中的血腥菜鳥,我無法獲得明確的解決方案。
我有一張地圖,上面分布着點。 當我單擊一個點時,我要縮放和平移到它。 到目前為止,還不錯,但是當我嘗試再次拖動和縮放它時,它將重置為zoomIdentity而不保留我手動設置的值。
編輯:這是一個工作示例: https : //codepen.io/brunofenzl/pen/pLxbjZ
我的代碼的相關部分:
// zoom initialization
this.zoom = d3.zoom()
.scaleExtent([1, 2])
.translateExtent([[0, 0], [width, height]])
.on('zoom', this.zoomed);
// zoom listener
Map.prototype.zoomed = function zoomed() {
if (d3.event) {
this.view.attr('transform', d3.event.transform);
}
}
// the function that zooms in
Map.prototype.selectFeature = function selectFeature(el) {
this.active = d3.select(el);
const bounds = this.active.node().getBBox();
const dx = bounds.width;
const dy = bounds.height;
const x = bounds.x + (bounds.width / 2);
const y = bounds.y + (bounds.height / 2);
const scale = Math.max(1, Math.min(8, 0.9 / Math.max(dx / this.width, dy / this.height)));
const translate = [(this.width / 2) - (scale * x), (this.height / 2) - (scale * y)];
this.view.transition()
.duration(750)
.attr("transform", "translate(" + translate + ")scale(" + scale + ")");
return null;
}
我已經嘗試了兩天的不同解決方案,但是無法正常工作。
任何幫助都超過贊賞!
長時間后,我找到了解決方案。 在我的selectFeature函數中,我應該更新緩存的縮放狀態,而不是直接設置transform屬性。 該解決方案的好處在於,它將觸發縮放事件,該事件將更新已經設置的縮放功能中的UI。
此處的工作示例: https : //codepen.io/brunofenzl/pen/zWmoWJ
為了更新緩存的轉換,我使用了自述文件中所述的d3.zoomIdentity
var t = d3.zoomIdentity.translate(x, y).scale(k);
因此,在我的情況下,修改后的代碼是:
this.view.transition()
.duration(750)
.call(
this.zoom.transform,
d3.zoomIdentity.translate(translate[0], translate[1]).scale(scale)
);
這種技術的缺點是,范圍約束無法再按預期工作,因此,例如,如果您的范圍小於新的縮放比例,則下次拖動或縮放時,縮放比例將跳至您的范圍允許的下一個可能的縮放值。 我已解決此問題,因為現在禁用了縮放范圍。 我希望這對其他人有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.