将d3js从v3升级到v4会导致缩放问题

时间:2016-08-07 16:46:01

标签: javascript d3.js d3v4

我正在使用d3js v3,我想升级到v4,但升级到v4会导致缩放为undefined

这是代码:

var zoom = d3.behavior.zoom().scaleExtent([1, 8]).on("zoom", zoomed);

控制台中显示错误:

index.html:192 Uncaught TypeError: Cannot read property 'zoom' of undefined

我使用此示例作为我的实现的参考:

https://bl.ocks.org/mbostock/6123708

代码@ Github页面:

http://jmargieh.github.io/NBA-shots-chart-d3js/

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

试试这个,有些东西已被重命名。

var margin = {top: -5, right: -5, bottom: -5, left: -5},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var zoom = d3.zoom()
    .scaleExtent([1, 10])
    .on("zoom", zoomed);

var drag = d3.drag()
    .subject(function(d) { return d; })
    .on("start", dragstarted)
    .on("drag", dragged)
    .on("end", dragended);

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.right + ")")
    .call(zoom);

var rect = svg.append("rect")
    .attr("width", width)
    .attr("height", height)
    .style("fill", "none")
    .style("pointer-events", "all");

var container = svg.append("g");

container.append("g")
    .attr("class", "x axis")
  .selectAll("line")
    .data(d3.range(0, width, 10))
  .enter().append("line")
    .attr("x1", function(d) { return d; })
    .attr("y1", 0)
    .attr("x2", function(d) { return d; })
    .attr("y2", height);

container.append("g")
    .attr("class", "y axis")
  .selectAll("line")
    .data(d3.range(0, height, 10))
  .enter().append("line")
    .attr("x1", 0)
    .attr("y1", function(d) { return d; })
    .attr("x2", width)
    .attr("y2", function(d) { return d; });

d3.tsv("dots.tsv", dottype, function(error, dots) {
  dot = container.append("g")
      .attr("class", "dot")
    .selectAll("circle")
      .data(dots)
    .enter().append("circle")
      .attr("r", 5)
      .attr("cx", function(d) { return d.x; })
      .attr("cy", function(d) { return d.y; })
      .call(drag);
});

function dottype(d) {
  d.x = +d.x;
  d.y = +d.y;
  return d;
}

function zoomed() {
  container.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}

function dragstarted(d) {
  d3.event.sourceEvent.stopPropagation();
  d3.select(this).classed("dragging", true);
}

function dragged(d) {
  d3.select(this).attr("cx", d.x = d3.event.x).attr("cy", d.y = d3.event.y);
}

function dragended(d) {
  d3.select(this).classed("dragging", false);
}

答案 1 :(得分:0)

对于缩放v3 vs v5(可能与转到v4相同),我在另一个相关的stackoverflow上发布了有关此内容的信息,如果这对访问此问题的人有用:dagre-d3 js Zoom Fit to all contents