【问题标题】:d3js scaling stroke widthd3js 缩放笔画宽度
【发布时间】:2018-07-21 01:34:01
【问题描述】:

我目前正在绘制一些箭头,并希望它们具有不同/缩放的笔划宽度(有些比其他的更胖) 我目前正在使用此代码,但笔画宽度不会改变。如果我硬编码一个像 5 这样的值,它确实会改变。 我在另一个代码中使用完全相同的缩放比例,但我正在缩放条形的高度(没有问题)。

这是我正在使用的一个小提琴:https://fiddle.jshell.net/42jdw2Lt/ 我想使用我标记为“num”的系列值来缩放我的笔画宽度。

    <!DOCTYPE html>
<meta charset="utf-8">

<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js">
</script>
<script src="http://d3js.org/topojson.v1.min.js"></script>
<script src="https://d3js.org/d3-selection-multi.v1.min.js"></script>

<script>

var svg = d3.select("body").append("svg")
 .attr("width", 1500)
 .attr("height", 1500);

var strwi = d3.scaleLinear()
          .domain([100, 400])
          .range([7,35])

var group = svg.append("g")

var series = [
             [{"x": 360, "y": 250, "num": 100}, {"x": 520, "y": 400, "num": 
             100}, {"x": 630, "y": 300, "num": 100}],
             [{"x": 71, "y": 45, "num": 200}, {"x": 32, "y": 39, "num": 
             200}, {"x": 43, "y": 70, "num": 200}],
             [{"x": 100, "y": 300, "num": 300}, {"x": 200, "y": 200, "num": 
             300}, {"x": 300, "y": 200, "num": 300}], [{"x": 101, "y": 202, 
             "num": 400}, {"x": 102, "y": 204, "num": 400}, {"x": 103, "y": 
             215, "num": 400}]
  ];

  var line = d3.line()
  .curve(d3.curveBasis)
  .x(function(d) { return d.x; })
  .y(function(d) { return d.y; });

   svg.append("svg:defs").append("svg:marker")
    .attr("id", "triangle")
    .attr("refX", 0)
    .attr("refY", 5)
    .attr("markerWidth", 14)
    .attr("markerHeight", 14)
    .attr("viewBox", "0 0 20 10")
    .attr("orient", "auto")
    .append("path")
    .attr("d", "M 0,0 L 10,5 L 0,10 z")
    .style("fill", "black");

    group.selectAll(".line")
    .data(series)
    .enter().append("path")
    .attr("class", "line")
    .attr("stroke-width", function(d) {return strwi(d); })
    .attr("stroke", "black")
    .attr("fill", "none")
    .attr("d", line)
    .attr("marker-end", "url(#triangle)");

   </script>

【问题讨论】:

    标签: d3.js scale stroke


    【解决方案1】:

    我刚刚对代码做了一个couple of changes

    • 我将stroke-width和其他一些属性设置为样式
    • 我使用系列的第一个元素及其num 属性来计算宽度

    代码现在看起来像这样,每个系列都有不同的粗细

    group.selectAll(".line")
        .data(series)
      .enter().append("path")
        .attr("class", "line")
        .style("stroke-width", function(d) {return strwi(d[0].num); })
        .style("stroke", "black")
      .style("fill", "none")
        .attr("d", line)
        .attr("marker-end", "url(#triangle)");
    

    【讨论】:

    • 哇,非常感谢,这正是我所需要的。我无法弄清楚 strwi(d[0].num) 部分。顺便说一句,您知道对箭头进行颜色编码的快速方法吗?如果我在我的数据中添加另一列(我们称之为“ID”),我可以使用该列将具有相同 ID 的所有箭头的笔划更改为一种颜色吗?
    • 没关系,我自己想出了一个 :) 再次感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-13
    • 1970-01-01
    相关资源
    最近更新 更多