【问题标题】:d3 mouse event, add circles on clickd3鼠标事件,单击时添加圆圈
【发布时间】:2020-10-23 20:09:18
【问题描述】:

我需要在我的代码中添加,当我点击它时,会添加更多不同半径的圆,我一直坚持到这一点

function dragstarted(event, d) {
  d3.select(this).raise().attr("stroke", "black");
}

function dragged(event, d) {
  d3.select(this).attr("cx", d.x = event.x).attr("cy", d.y = event.y);
}

function dragended(event, d) {
  d3.select(this).attr("stroke", null);
}

const drag = d3.drag()
  .on("start", dragstarted)
  .on("drag", dragged)
  .on("end", dragended);

const height = 300,
  width = 700
radius = 20

const svg = d3.select("svg")
  .attr("viewBox", [0, 0, width, height])
  .attr("stroke-width", 2);

const circles = d3.range(10).map(i => ({
  x: Math.random() * (width - radius * 1) + radius,
  y: Math.random() * (height - radius * 1) + radius,
}));

svg.selectAll("circle")
  .data(circles)
  .join("circle")
  .attr("cx", d => d.x)
  .attr("cy", d => d.y)
  .attr("r", radius)
  .attr("fill", (d, i) => d3.schemePastel1[i % 100])
  .call(drag);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.2.0/d3.min.js"></script>
<svg></svg>

我需要创建类似的东西,可以移动圆圈并通过单击添加更多圆圈

【问题讨论】:

    标签: html reactjs d3.js canvas


    【解决方案1】:

    考虑以下几点:

    • 将绘图移至可调用函数
    • 点击时,使用事件的clientX 和clientY 将新圆圈推送到圆圈数组并重绘。

    function dragstarted(event, d) {
      d3.select(this).raise().attr("stroke", "black");
    }
    
    function dragged(event, d) {
      d3.select(this).attr("cx", d.x = event.x).attr("cy", d.y = event.y);
    }
    
    function dragended(event, d) {
      d3.select(this).attr("stroke", null);
    }
    
    const drag = d3.drag()
      .on("start", dragstarted)
      .on("drag", dragged)
      .on("end", dragended);
    
    const height = 300,
      width = 700,
      maxRadius = 20;
    
    const circles = d3.range(10).map(i => ({
      x: Math.random() * (width - maxRadius * 2) + maxRadius,
      y: Math.random() * (height - maxRadius * 2) + maxRadius,
      radius: Math.random() * (maxRadius - 2) + 2,
    }));
    
    const svg = d3.select("svg")
      .attr("viewBox", [0, 0, width, height])
      .attr("stroke-width", 2)
      .on("click", (event) => {
        console.log(event);
        circles.push({
          x: event.clientX,
          y: event.clientY,
          radius: Math.random() * (maxRadius - 2) + 2,
        });
        drawCircles();
      })
    
    function drawCircles() {
      svg.selectAll("circle")
        .data(circles)
        .join("circle")
        .attr("cx", d => d.x)
        .attr("cy", d => d.y)
        .attr("r", d => d.radius)
        .attr("fill", (d, i) => d3.schemePastel1[i % 9])
        .call(drag);
    }
    
    drawCircles();
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.2.0/d3.min.js"></script>
    <svg></svg>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-16
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 2017-10-06
      • 1970-01-01
      • 1970-01-01
      • 2013-12-03
      相关资源
      最近更新 更多