使用d3js缩放特定元素

时间:2014-03-05 19:14:39

标签: javascript html d3.js

我最近刚刚找到了d3js和这个示例代码块,在寻找放大元素的好方法:the example。我正在尝试使用相同的缩放方法,但不是使用json来填充svg和body,我只想放大特定的html元素。我是新手使用d3所以我不确定究竟是什么我做错了,但到目前为止我的代码是:

JS:

window.onload=function(){
  var width = 400,
    height = 400,
    centered;

  var projection = d3.geo.albersUsa()
    .scale(1070)
    .translate([width / 2, height / 2]);

var path = d3.geo.path()
    .projection(projection);

var svg = d3.select("body")
    .append("svg")
    .attr("width", width)
    .attr("height", height)
    .on("click", clicked);
var circle = svg.append("circle")
         .attr("class", "logo")
         .attr("cx", 225)
         .attr("cy", 225)
         .attr("r", 20)
         .style("fill", "transparent")      
         .style("stroke", "black")    
         .style("stroke-width", 0.25)
         .attr("d", path)
         .on("click", clicked)
          .on("mouseout", function(){ 
               d3.select(this)
                   .style("fill", "transparent");
         });

function clicked(d) {
  console.log("clicked");
  var x, y, k;

  if (d && centered !== d) {
    var centroid = path.centroid(d);
    x = centroid[0];
    y = centroid[1];
    k = 4;
    centered = d;
  } else {
    x = width / 2;
    y = height / 2;
    k = 1;
    centered = null;
  }

  circle.selectAll("path")
      .classed("active", centered && function(d) { return d === centered; });

  circle.transition()
      .duration(750)
      .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")scale(" + k + ")translate(" + -x + "," + -y + ")")
      .style("stroke-width", 1.5 / k + "px");
}
        }

HTML:

<script src="d3.min.js"></script>
<script src="index.js"></script>
</head>
<body>
<svg id="mySvg" width="80" height="80">
      <defs id="mdef">
        <pattern id="image" x="0" y="0" height="40" width="40">
          <image x="0" y="0" width="40" height="40" xlink:href="image1.png"></image>
        </pattern>
  </defs>

</body>

这是我目前所拥有的fiddle。如您所见,它调用click函数并设置笔触宽度的样式,但它不会缩放对象。

0 个答案:

没有答案