d3鼠标事件,单击时添加圆圈

丹尼尔·阿布雷戈

我需要在代码中添加一些内容,当我单击该代码时,会添加更多的圆和不同半径的圆,到现在为止

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>

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

在此处输入图片说明

鲁本·赫斯鲁特(Ruben Helsloot)

考虑以下:

  • 将图形移至可调用的功能
  • 点击后,按新的圆圈圈的阵列,使用clientXclientY事件并重绘。

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>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章