D3。为什么我的小组翻译不起作用?

时间:2015-06-21 17:22:46

标签: d3.js

我的目标是翻译一组带有翻译的svg元素。它不起作用。这是代码:

创建SVG容器

// create svg container
canvas = d3.select("body").append("svg")
    .attr("width",   canvasBBox.width)
    .attr("height", canvasBBox.height);

附加x = 200,y = 200

的翻译
// apply a transform
canvas.append("g")
    .attr("transform", function(d) { return scarpa.translate(200, 200); });

添加一个方框

  // render a background
    canvas.append("rect")
        .attr("x", 0)
        .attr("y", 0)
        .attr("width",   canvasBBox.width)
        .attr("height", canvasBBox.height)
        .style("opacity", 1)
        .style("fill", function(d) { return scarpa.rgb_SVG(0,255,0); });

添加y轴

// render y-axis
canvas.append("g")
    .attr("class", "y axis")
    .append("line")
    .attr("stroke", function(d) { return scarpa.grey_SVG(64); })
    .attr("x1", histogram.xScale(0))
    .attr("y1", 0)
    .attr("x2", histogram.xScale(0))
    .attr("y2", canvasBBox.height);

框+ y轴线永远不会翻译。为了进行健全性检查,我将翻译方向应用到了框中并且确实进行了翻译。叹息。

我假设组翻译意味着一个局部坐标系,其中x = y = 0将是翻译坐标系的原点。没有?我在这里缺少什么?

1 个答案:

答案 0 :(得分:4)

问题是,.append()函数不会更改调用它的选择,而是返回一个新选择。

因此,g元素会附加到svg,而rect也会附加到svg,而不会附加到已翻译的g元素中。如果您检查svg输出,则应该看到这一点。

有两种可能的解决方案: 1:如果要翻译所有内容,请在第一个语句中附加g元素,如下所示:

var canvas = d3.select("body").append("svg")
    .attr("width",   canvasBBox.width)
    .attr("height", canvasBBox.height)
  .append("g")
    .attr("transform", function(d) { return scarpa.translate(200, 200); });

canvas.append("rect")
    .attr("x", 0)
    .attr("y", 0)
    .attr("width",   canvasBBox.width)
    .attr("height", canvasBBox.height)
    .style("opacity", 1)
    .style("fill", function(d) { return scarpa.rgb_SVG(0,255,0); });

canvas.append("g")
    .attr("class", "y axis")
  .append("line")
    .attr("stroke", function(d) { return scarpa.grey_SVG(64); })
    .attr("x1", histogram.xScale(0))
    .attr("y1", 0)
    .attr("x2", histogram.xScale(0))
    .attr("y2", canvasBBox.height);

2:如果你想在翻译组之外追加一些东西, 将groupselection分配给一个新变量,如下所示:

var canvas = d3.select("body").append("svg")
    .attr("width",   canvasBBox.width)
    .attr("height", canvasBBox.height);

var canvasGroup = canvas.append("g")
    .attr("transform", function(d) { return scarpa.translate(200, 200); });

canvasGroup.append("rect")
    .attr("x", 0)
    .attr("y", 0)
    .attr("width",   canvasBBox.width)
    .attr("height", canvasBBox.height)
    .style("opacity", 1)
    .style("fill", function(d) { return scarpa.rgb_SVG(0,255,0); });

canvasGroup.append("g")
    .attr("class", "y axis")
  .append("line")
    .attr("stroke", function(d) { return scarpa.grey_SVG(64); })
    .attr("x1", histogram.xScale(0))
    .attr("y1", 0)
    .attr("x2", histogram.xScale(0))
    .attr("y2", canvasBBox.height);
相关问题