javascript - 使用 ES6 类在 D3 可重用图表中添加缩放功能
问题描述
我正在切换一个可重用的 D3 v5 图表以使用 ES6 类,并且在实现更新变量的函数(如缩放函数)时遇到了麻烦。到目前为止,我有一张工作地图:
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()
使用这些类,我尝试在类的一部分中声明缩放并调用移动表单并将函数.on("zoom", this.move)
附加call
到 SVG,如上面注释中标记的那样。但是我 Uncaught TypeError: Cannot read property 'style' of undefined at SVGSVGElement.move
在引用时得到了移动功能this.plot
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);
}
解决方案
你需要绑定this
const zoom = d3.zoom()
.scaleExtent([1, 9])
.on("zoom", this.move.bind(this));
console.logthis
里面的move()
推荐阅读
- cmd - 如何在 XCOPY 上使用递归?
- sql - 将列中的 SQL 数据转换为数组
- r - 你如何计算R中数据框中列表中的项目数?
- azure-functions - 处理 CSV 文件的 Azure 函数
- java - 如何导入此 API Java?类路径?
- c# - C# WebClient.DownloadString 不返回整个网页源
- syntax - Antlr 奇怪的括号语法
- project-reactor - 在 Reactor Sinks.Many() 中相当于 EmitterProcessor onCancel
- java - 使用 String 参数进行锁定时,锁定的对象是什么?
- javascript - 如何停止在检测表单是否已提交的函数之外启动的 setTimeout?