d3.js奇数旋转行为 [英] d3.js Odd Rotation Behavior

查看:144
本文介绍了d3.js奇数旋转行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个JS项目的早期阶段。一切都进行得很好,除了一个形状的定位。所讨论的形状是深蓝色菱形(正方形旋转45度)。我可以得到屏幕上的方块没有问题,但是当我添加:

I'm in the early stages of a JS project. Everything is going fine so far except for the positioning of one shape. The shape in question is a teal diamond (square rotated 45 degrees). I can get the square on the screen no problem, but when I add:

    .attr("transform", "rotate(45)")

正方形正常旋转,但向屏幕左侧移动, :

the square rotates properly, but shifts towards the left portion of the screen, like this:

>

我不知道是什么原因导致这种情况发生。如果有帮助,下面是一些产生这个结果的代码:

I am not sure what is causing this to happen. If it helps, here is some of the code that produced this result:

var svg = d3.select("body")
            .append("svg")
            .attr("width", w)
            .attr("height", h);
        svg
            .append("rect")
            .attr("transform", "rotate(45)")
            .attr("x", 250)
            .attr("height", w / 10)
            .attr("width", w / 10)
            .attr("fill", "teal")

注意:如果我输入y属性,则正方形完全消失。

Note: If I put the "y" attribute in, the square disappears completely.

是什么原因造成的?

推荐答案

旋转矩形时,还要旋转它的坐标系。因此,当您以后沿x轴移动250个时,您实际上沿着45度轴移动250个单位 - 旋转的结果。

When you rotate the rect, you also rotate its coordinate system. So when you later move it 250 along the x axis, you're actually moving it 250 units along a 45 degree axis -- the result of the rotation.

规则,当你像对 rotate 所做的那样引入 transform 属性时,应该通过此属性执行所有的转换。因此,您需要使用 translate ,而不是使用x属性。然后它看起来像这样:

As a rule, when you introduce a transform attribute as you did for rotate, you should do all your transformation via this attribute. So, you need to use translate instead of using the "x" attribute. Then it would look like this:

svg
  .append("rect")
  .attr("transform", "translate(250, 0) rotate(45)")
  // remove this: .attr("x", 250)
  .attr("height", w / 10)
  ...

这会得到你想要的结果。现在注意转换的顺序很重要:如果你的转换rotate(45)translate(250,0)(即先旋转然后翻译)得到相同,错误的结果你以前。这是因为当您先旋转时,您的翻译会像以前一样沿着旋转的x轴发生。

This gets you the results I think you're looking for. Now note that the order of transformations matters here: if your transform was "rotate(45) translate(250, 0)" (i.e. first rotate then translate), you'd get the same, wrong results you got before. That's because when you rotate first, your translation happens, as before, along a rotated x axis.

这篇关于d3.js奇数旋转行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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