D3.js中的随机翻译 [英] Random Translation in D3.js

查看:34
本文介绍了D3.js中的随机翻译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在svg中的随机位置附加"g".下面是我的代码.令人惊讶的是,所有10个'g's都绘制在同一位置上.我在第5行中指定了随机位置,但所有g的x和y都相同.我在做什么错了?

I am trying to append 'g' in random locations within an svg. Below is my code. Surprisingly, all the 10 'g's are being drawn on the same position. I specified random position in line 5 but all g got the same x and y. What am I doing wrong?

const art = svg.selectAll('g')
.data(d3.range(10))
.enter()
.append('g')
.attr("transform", `translate(${d3.randomInt(padding, width-padding)()},${d3.randomInt(padding, height-padding)()})`) //this line
.selectAll('snowflake')
.data(d3.range(6))
.enter()
.append('line')
.style("stroke", "lightblue")
.style("stroke-width", 5)
.attr("x1", 0)
.attr("y1", 0)
.attr("x2", d=>r*Math.cos(d*Math.PI/3))
.attr("y2", d=>r*Math.sin(d*Math.PI/3))

推荐答案

如果 .attr() .style()的第二个参数是一个函数,则 .attr()/ .style()将对所选内容中的每个元素执行一次.如果第二个参数的值为字符串或数字(某个常量值),则该常量值将传递给 .attr()/ .style().无论哪种方式, .attr() .style()都只能调用一次.

If the second parameter of .attr() or .style() is a function, .attr()/.style() will execute it once for every element in the selection. If the second parameter evaluates to be a string or a number (some constant value), that constant value will be passed to .attr()/.style(). Either way, the .attr() and .style() are called only once.

您的代码属于第二种情况:您没有将函数传递给 .attr(),而是传递了一个字符串:

Your code falls into the second case: you aren't passing a function to .attr(), you are passing a single string:

`translate(${d3.randomInt(padding, width-padding)()},${d3.randomInt(padding, height-padding)()})`

您不能将未经评估的这一行代码传递给任何方法或函数,必须先对它进行评估,然后传递给 .attr()方法.由于 .attr()方法仅被调用一次,因此您只能获得一个随机数.

You cannot pass this line of code unevaluated to any method or function, it must be evaluated and then passed to the .attr() method. As the .attr() method is called only once, you only get one random number.

如果您创建了一个函数来获取随机字符串:

If you had created a function to get you your random string:

 function random() {
      return `translate(${d3.randomInt(padding, width-padding)()},${d3.randomInt(padding, height-padding)()})`
 }

您正在执行以下操作:

select.attr("translate", random()); // pass the return value to .attr (a string) 

但是您想要做的是传递函数本身:

But what you want to be doing is passing the function itself:

select.attr("translate", random);  // pass the function itself to .attr so it can execute it

此方法仍然只执行一次,但是在内部它会为选择中的每个元素调用 random .

This method is still only executed once, but internally it will call random for each element in the selection.

因此您可以执行上述操作,或使用匿名函数:

So you can do like the above, or use an anonymous function:

 selection.attr("translate",function() { /* return random translate */ })

这篇关于D3.js中的随机翻译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆