gpt4 book ai didi

javascript - 使用 ES6 类在 D3 可重用图表中添加缩放功能

转载 作者:行者123 更新时间:2023-11-28 10:40:18 25 4
gpt4 key购买 nike

我正在将可重用的 D3 v5 图表切换为使用 ES6 类,但在实现更新变量(例如缩放函数)的函数时遇到问题。到目前为止我有一个工作 map :

class myMap{
constructor(args = {}){

this.data = args.data;
this.topo = args.topo;
this.element =document.querySelector(args.element);
this.width =args.width || this.element.offsetWidth;
this.height = args.height || this.width / 2;


this.setup();
}

setup(){
this.projection = d3.geoMercator()
.translate([(this.width/2), (this.height/2)])
.scale( this.width / 2 / Math.PI);

this.path = d3.geoPath().projection(this.projection);

// zoom fuction inserted here
this.element.innerHTML ='';
this.svg =d3.select(this.element).append("svg")
.attr("width", this.width)
.attr("height", this.height)
//.call(zoom)
.append("g");

this.plot = this.svg.append("g");
d3.json(this.topo).then( world => {

var topo = topojson.feature(world, world.objects.countries).features;

this.draw(topo);
});

}


draw(topo){

var country = this.plot.selectAll(".country")
.data(topo);

country.enter().insert("path")
.attr("class", "country")
.attr("d", this.path)
.attr('id', 'countries')
.attr("fill", #cde)
.attr("class", "feature");

}
//move(){} goes here

}

使用以下方式调用:

const chart = new myMap({
element: '#map',
data: DATA_IN_JSON,
topo:"../../../LINK_to_topojsonfile"});

使用函数时,我通过使用变量并调用 move 函数添加了缩放功能,并将 .call(zoom) 附加到 SVG:

var zoom = d3.zoom()
.scaleExtent([1, 9])
.on("zoom", move);

function move() {
g.style("stroke-width", 1.5 / d3.event.transform.k + "px");
g.attr("transform", d3.event.transform);
}

使用我尝试在类的 setup() 部分声明 Zoom 的类,并调用移动形式 .on("zoom", this.move) 并附加SVG 的 call 函数,如上面注释中标记的那样。但在引用 this.plot

时,我在 move 函数中收到 Uncaught TypeError: Cannot read property 'style' of undefined at SVGSVGElement.move
const zoom = d3.zoom()
.scaleExtent([1, 9])
.on("zoom", this.move);

move() {
this.plot
.style("stroke-width", 1.5 / d3.event.transform.k + "px");
this.plot
.attr("transform", d3.event.transform);
}

最佳答案

你需要绑定(bind)这个

const zoom = d3.zoom()
.scaleExtent([1, 9])
.on("zoom", this.move.bind(this));

console.log move() 内的 this

关于javascript - 使用 ES6 类在 D3 可重用图表中添加缩放功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52716205/

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