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

D3.js交互图表需求:延长拖动滑块、实现数值转字母映射输出

D3.js交互图表修改方案

需求说明

  • 拉长拖动滑块(range输入控件)至指定长度(示例中红线对应长度)
  • 添加方块输出区域,拖动滑块时将数值映射为对应字母(如数值2对应B,3对应C)并显示

修改后完整代码

HTML

<center>
  <div class="centered">
    Number of side of the polygon.
    <script src="https://d3js.org/d3.v5.js"></script>
    <p>
      <input id="ranger" type="range" min="3" max="32" value="5">
      <label for="ranger"></label>
    </p>
    <!-- 新增字母显示方块 -->
    <div id="letter-box" class="letter-box"></div>
  </div>
</center>
</body>

CSS

svg {
  display: block;
  margin: auto;
  width: 300px;
  height: 300px;
} 
/* 拉长滑块至目标长度 */
#ranger {
  width: 300px;
}
/* 字母方块样式 */
.letter-box {
  width: 60px;
  height: 60px;
  border: 2px solid black;
  margin: 10px auto;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  font-weight: bold;
}

JavaScript

// 基础初始化代码
const svg = d3.select("body")
  .append("svg")
    .attr("width", 500)
    .attr("height", 500);
    
const circle = svg.append("circle")
    .attr("cx", "150")
    .attr("cy", "150")
    .attr("r", "100")
    .attr("fill", "none")
    .attr("stroke", "black");
    
const polygon = svg.append("polygon")
    .attr("fill", "none")
    .attr("stroke", "blue");
    
const circleElement = circle.node();
const ranger = d3.select("#ranger").on("input", update);
const label = d3.select("label");
// 获取字母方块元素
const letterBox = d3.select("#letter-box");

// 核心逻辑更新函数
function update() {
  let count = ranger.node().value;
  label.text(count);
  // 数值转对应字母:A对应1、B对应2,以此类推
  const letter = String.fromCharCode(64 + parseInt(count));
  letterBox.text(letter);
  
  // 多边形顶点计算逻辑
  const step = circleElement.getTotalLength() / count; 
  const data = Array.from({length: count}, (_, i) => {
    const point = circleElement.getPointAtLength(i * step);
    return `${point.x},${point.y}`; 
  });
  polygon.attr("points", data.join(" "));
}

// 初始化执行一次
update();

修改说明

  1. 拉长滑块:通过CSS给#ranger设置width: 300px,和SVG画布宽度对齐,达到需求中的长度效果
  2. 字母显示方块:
    • 在HTML中新增用于显示字母的div容器
    • 用CSS定义方块的边框、尺寸和文字居中样式
    • 在JS的update函数中,通过ASCII码转换逻辑将数值映射为对应字母,实时更新方块内的文本内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 12:24:21