9

私はJSプロジェクトの初期段階にいます。1 つの形状の配置を除いて、これまでのところすべて順調に進んでいます。問題の形状はティール ダイヤモンド (正方形を 45 度回転させたもの) です。問題なく画面に正方形を表示できますが、追加すると:

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

正方形は適切に回転しますが、次のように画面の左側に移動します。

ここに画像の説明を入力

何が原因なのかわかりません。それが役立つ場合は、この結果を生成したコードの一部を次に示します。

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」属性を入れると、四角が完全に消えます。

これは何が原因ですか?見えないだけで何か悪いことをしたのでしょうか?

4

3 に答える 3

18

四角形を回転すると、その座標系も回転します。後で x 軸に沿って 250 移動すると、実際には 45 度の軸に沿って 250 単位移動します。これは回転の結果です。

原則として、 で行ったようにtransformアトリビュートを導入する場合はrotate、このアトリビュートを介してすべての変換を行う必要があります。translateしたがって、属性を使用する代わりに使用する必要があり"x"ます。次に、次のようになります。

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 軸に沿って移動が行われるためです。

于 2012-06-11T18:24:39.140 に答える
11

SVG では、変換の原点を設定して、中心から回転させる必要があります。

.attr("transform", "rotate(45, 250, 100)");

250, 100四角形の x と y の位置から半径を引いた場所はどこですか。全部合わせると・・・こんな感じ。

var svg = d3.select("body")
            .append("svg")
            .attr("width", 400)
            .attr("height", 300);
        svg
            .append("rect")
            .attr("transform", "rotate(30,"+ (diamond.x+diamond.width/2) + ","+ (diamond.y+diamond.width/2) +")")
            .attr("x", diamond.x)
            .attr("y", diamond.y)
            .attr("height", diamond.width)
            .attr("width", diamond.width)
            .attr("fill", "teal")​

ここでデモを見ることができます:

http://jsfiddle.net/uwM8u/

于 2012-06-11T18:35:50.613 に答える
0

Here is an approach slightly different from the answer Duopixel gave. Here you are not repeating the calculations for X and Y. In Duopixel's example, its a trivial improvement since he is merely referencing a structure. Its often the case that X and Y are functions and I would not want to maintain that loging in two places. This approach allows you to set X and Y a node, then rotate on the center of said node.

You may find that after the rotation, you still want to tweak the final position, which could be done with another transform, or in the case of TEXT, you can use dx, dy.

    svgNode.attr("transform", function (d) {

                    var w = +d3.select(this).attr("x") +  (this.getBBox().width / 2) ;
                    var h = +d3.select(this).attr("y") + (this.getBBox().height / 2);

                    return  "rotate(90," + w + "," + h + ")";

                })
于 2014-05-21T17:29:44.407 に答える