这之前已经回答过了,但没有一个答案适合我的问题
问题是。我正在编写一个非常简单的代码,将选定的圆移动到父元素中的随机位置。如果我这样做:
...
circle.attr('cx', nx)
.attr('cy', ny)
...
nx
并ny
新计算的x,y坐标,它可以完美运行。现在,如果我使用transition()
,我收到消息Error: <circle> attribute cy: Expected length, "NaN"
。最奇怪的事情只发生在cy
吸引力上。使用cx
或r
attrs 它完美运行,我正在尝试的代码是:
...
circle.transtion()
.attr('cx', nx)
.attr('cy', ny)
...
我认为这可能与attr()
返回的内容有关,所以我改为:
...
circle.transtion()
.attr('cy', ny)
.attr('cx', nx)
...
并且得到了同样的错误,即使我这样做
...
circle.transtion()
.attr('cy', ny)
...
它不起作用,但如果我这样做
...
circle.transtion()
.attr('cx', nx)
...
它完美地工作
所以我不知道要寻找什么
当然,cx
和cy
都有有效的值,我什至尝试.attr('cy', cx)
认为它可能以某种方式具有 NaN 值
完整代码:
ancho = d3.select('#canvas').style('width').slice(0, -2)
alto = d3.select('#canvas').style('height').slice(0, -2)
cir = d3.select('#cir')
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
d3.select('#boton').on('click', function() {
let nx = getRandomInt(ancho)
let ny = getRandomInt(alto)
console.log(nx, ny);
cir.transition()
.attr('cx', nx)
.attr('cy', ny)
.attr('r', getRandomInt(200))
})
button {
width: 50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<button id="boton" type="button">Click</button>
<svg id="canvas" width="100%" height="300px">
<circle id="cir" cy="10" cx="10" r="10">
</svg>
非常感谢您的片段
我解决了它,但我真的不明白为什么会发生这种情况。正如您在 Alex L 放置的上一个代码段中看到的那样,它确实适用于代码段。这正是我想做的。现在,如果我将该代码复制到我的页面上(只是假设我有一些我无法弄清楚的错误(,它也不起作用,并产生相同的错误。
那我做了什么?
d3.select('#boton').on('click', function() {
let nx = getRandomInt(ancho)
let ny = getRandomInt(alto)
console.log(nx, ny);
cir.transition()
.attr('cx', nx.toString())
.attr('cy', ny.toString())
.attr('r', getRandomInt(200))
})
我不明白为什么这有效。这是荒谬的。您可以向attr
传递一个整数,例如.attr('cx', 100)
并且有效,但是如果我传递包含整数的 var,它会给我错误消息。
如果我取出.transition()
它适用于变量,那么
工作示例(我认为(。它按照我所期望的那样工作,没有任何Javascript更改?(我刚刚添加了正确的 svg 标签等(
也工作代码笔:https://codepen.io/Alexander9111/pen/KKVZMeR
在Chrome 83.0.4103.116,FireFox 77.0.1和Edge 42.17134.1098.0上为我工作
ancho = d3.select('#canvas').style('width').slice(0, -2)
alto = d3.select('#canvas').style('height').slice(0, -2)
cir = d3.select('#cir')
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
d3.select('#boton').on('click', function() {
let nx = getRandomInt(ancho)
let ny = getRandomInt(alto)
console.log(nx, ny);
cir.transition()
.attr('cx', nx)
.attr('cy', ny)
.attr('r', getRandomInt(200))
})
button {
width: 50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<button id="boton" type="button">Click</button>
<svg id="canvas" width="100%" height="300px">
<circle id="cir" cy="10" cx="10" r="10">
</svg>