D3 zoom - 无法读取属性' apply'未定义的

时间:2016-02-12 07:37:55

标签: javascript jquery d3.js

我跟随this tutorial学习如何缩放svg。这是我的代码。



var vis = d3.select("#svg-canvas").append("svg")
  .attr("width", "550")
  .attr("height", "400")
  .append("g")
  .attr("class", "svg-container")
  .attr("transform", "translate(550,400)")
  .call(zoom);

vis.append("rect")
  .attr("x", 10)
  .attr("y", 10)
  .attr("width", 100)
  .attr("height", 40)
  .style("fill", "#444");

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

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

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id="svg-canvas">

</div>
&#13;
&#13;
&#13;

但我在控制台中收到错误,说明如下

Uncaught TypeError: Cannot read property 'apply' of undefined

我做错了什么?

1 个答案:

答案 0 :(得分:2)

使用.call(缩放)时,变量缩放未定义。

应首先定义。

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

var vis = d3.select("#svg-canvas").append("svg")
  .attr("width", "550")
  .attr("height", "400")
  .append("g")
  .attr("class", "svg-container")
  .attr("transform", "translate(550,400)")
  .call(zoom);

vis.append("rect")
  .attr("x", 10)
  .attr("y", 10)
  .attr("width", 100)
  .attr("height", 40)
  .style("fill", "#444");

function zoomed() {
  d3.select(".svg-container").attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id="svg-canvas">

</div>
&#13;
&#13;
&#13;