2015-12-29 95 views
1

我有一个使用d3.js和svg表示的网格。 我想要做的是在点击图块时更改图块和所有相邻图块的颜色。 我想知道最好的方式来选择毗邻点击的瓷砖。 到目前为止我的代码:按属性选择d3.js数据元素

var w = 960, 
    h = 500, 
    z = 20, 
    x = w/z, 
    y = h/z; 

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

svg.selectAll("rect") 
    .data(d3.range(x * y)) 
    .enter().append("rect") 
    .attr("transform", translate) 
    .attr("position", pos) 
    .attr("width", z) 
    .attr("height", z) 
    .attr("clicked", false) 
    //.on("mouseover", mouseover) 
    .on("click", click) 
    .style("stroke", "rgb(6,120,155)") 
    .style("stroke-width", 2); 
    .style("fill", "rgb(255, 255, 255)") 


function translate(d) { 
    return "translate(" + (d % x) * z + "," + Math.floor(d/x) * z + ")"; 
} 

function pos(d) { 
    return [ (d % x) * z , Math.floor(d/x) * z ]; 
} 

function click(d) { 
    var currentColor = this.style.fill; 
    var clickedYet = d3.select(this).attr("clicked"); 
    currentColor = currentColor == "rgb(255, 255, 255)" ? "rgb(255, 0, 255)" : "rgb(255, 255, 255)"; 


    d3.select(this) 
    .attr("clicked", true) 
    .transition() 
     .style("fill", currentColor); 

} 

什么我不知道,是是否可以通过属性位置来选择瓷砖/“矩形”?或者如果我应该考虑一个完全不同的方法?

+0

我会为每个编码位置的元素(即“vertical-1”和“horizo​​ntal-5”或类似的东西)分配类。然后你可以使用这些类来选择正确的元素。 –

+0

@LarsKotthoff谢谢,可能不得不为此,目前我只是想了解它是如何工作的,但我的目标是想象网格上的搜索算法,例如aa bfs,您认为这是一个合理的方法? – user3636636

+0

听起来对我来说很合理。 –

回答

0

你能做到这样(选择同一行中的所有矩形)

我评论的代码为更好地理解算法。

function click(d) { 
    var currentColor = this.style.fill; 
    //this will give the data associated with the rectangle 
    var clickeddata = d3.select(this).data(); 
//this will give the row to be highlihted 
    var row = parseInt(clickeddata/x); 
    //current color calculation 
    currentColor = currentColor == "rgb(255, 255, 255)" ? "rgb(255, 0, 255)" : "rgb(255, 255, 255)"; 
    //iterate through all the rectangle 
    d3.selectAll("rect")[0].forEach(function(r){ 
    //all rectangle with same row 
    if(parseInt(d3.select(r).data()/x) == row){ 
     //make it color as it is in the same row 
     d3.select(r) 
     .attr("clicked", true) 
     .transition() 
      .style("fill", currentColor);  
    } 
    }); 

工作代码here