You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何调整D3.js v5中二十面体的顶点大小?

调整D3.js二十面体顶点显示大小的解决方案

你当前用path元素渲染MultiPoint地理数据展示顶点,但path默认仅记录点的坐标位置,不会生成有面积的图形,因此CSS的stroke属性无法改变顶点大小。以下是两种可行的解决方法:

方法1:修改GeoPath的Stream函数,绘制带大小的顶点

通过自定义投影的stream方法,在处理点时生成圆形路径,通过半径参数控制顶点大小:

  1. 定义顶点半径,修改path的stream逻辑:
var pointRadius = 3; // 自定义顶点半径,按需调整
var projection = d3.geoOrthographic().scale(240);

var path = d3.geoPath().projection({
  stream: function(out) {
    return {
      point: function(x, y) {
        var p = projection([x, y]);
        // 绘制圆形路径代替单纯的点
        out.moveTo(p[0] + pointRadius, p[1]);
        out.arc(p[0], p[1], pointRadius, 0, 2 * Math.PI);
      },
      lineStart: function() {
        out.lineStart();
      },
      lineEnd: function() {
        out.lineEnd();
      },
      polygonStart: function() {
        out.polygonStart();
      },
      polygonEnd: function() {
        out.polygonEnd();
      }
    };
  }
});
  1. 保留原有CSS样式,可额外调整描边宽度:
.point {
  fill: #000;
  stroke: #fff;
  stroke-width: 1; /* 可选,调整描边宽度 */
}

方法2:改用Circle元素渲染顶点(更直观灵活)

直接用SVG的circle元素代替path展示顶点,能更直接地控制大小:

  1. 替换原有的顶点渲染代码:
// 移除原来的point path代码,替换为以下内容
const points = icosahedron_points();
var point = svg.selectAll(".point")
  .data(points)
  .enter()
  .append("circle")
  .attr("class", "point")
  .attr("r", 3); // 直接设置顶点半径
  1. 修改refresh函数,更新每个顶点的位置:
function refresh() {
  edge.attr("d", path);
  face.attr("d", path);
  // 更新circle的坐标
  point.attr("cx", d => projection(d)[0])
       .attr("cy", d => projection(d)[1]);
}

这种方法无需修改GeoPath逻辑,后续调整顶点大小只需修改r属性的值即可,维护更简单。

内容的提问来源于stack exchange,提问作者Lidiya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 04:10:56