2015-06-21 49 views
2

我的目標是用翻譯翻譯一組svg元素。它不工作。下面是代碼:D3。爲什麼我的小組翻譯無法正常工作?

創建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內的局部座標系將是翻譯後的座標系的原點。沒有?我在這裏錯過了什麼?

回答

3

問題是,.append()函數不會更改它所調用的選擇,但會返回一個新選擇。

因此g元件被附加到svgrect得到也附加到翻譯g元件內部的svg而不是。你應該看到這個,如果你檢查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:如果你想追加翻譯之外的東西組, 將組選擇分配給一個新變量,如下所示:

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); 
+0

jhinzmann,您的解決方案1是我的原始代碼。 – dugla

+1

如果仔細觀察,您會發現我通過方法鏈將前兩個語句組合成一個語句。這樣,返回的選擇'append(「g」)''而不是'append(「svg」)'將被存儲在'canvas'變量 – jhinzmann

+0

實際上你的嵌套轉換解決方案是2不是1.我試過它和它的工作。請讓其他人一起閱讀。乾杯。 – dugla

相關問題