2017-10-14 71 views
1

在使用d3.js時仍然相當缺乏經驗,我碰到了一個障礙。 希望有人能幫助我。d3.js v4:如何在鼠標點擊節點後顯示圖像

我試圖在鼠標單擊圖形中的節點時顯示圖片。 理想情況下,我想單擊幾個節點並顯示圖像。雙擊節點應該刪除圖像。點擊背景將刪除所有顯示的圖像。但一次只能一步。

我到目前爲止所做的是: 成功使用工具提示。當鼠標點擊它時,我也能夠改變圓形節點的大小。

我用作玩具項目邁克·博斯托克的力導向圖示例:https://bl.ocks.org/mbostock/4062045。基於Web的,我能夠將圖片添加到所有節點上的例子 我使用d3.js v4的

Add different images for nodes in d3 v4 network graph

我試圖調整這個例子來我的需求。首先我說:

var defs = svg.append('defs'); 

進一步:

var node = svg.append("g") 
.attr("class", "nodes") 
.selectAll("circle") 
.data(graph.nodes) 
.enter() 
.append("circle") 
.attr("r", 5) 
.attr("fill", function(d) { return color(d.group); }) 
.call(node_drag) 
.on("click", function(d){ 
    defs.append("pattern") 
    .attr("x", 0) 
    .attr("y", 0) 
    .attr("width", 12) 
    .attr("height", 12) 
    .append("image") 
    .attr("xlink:href", 'https://assets-cdn.github.com/images/modules/open_graph/github-octocat.png') 
    .attr("width", 12) 
    .attr("height", 12) 
    .attr("x", 0) 
    .attr("y", 0); 
}) 

在我的瀏覽器的HTML表示圖像添加:

image of html

但圖像沒有在顯示瀏覽器。

在這一點上,我轉向你,希望得到一些提示,我點擊鼠標光標時如何完成將圖像顯示爲節點。

任何輸入被高度讚賞, 馬庫斯

回答

0

你的檢查員是表示將圖像附加在該模式,但它從未被連接到圓元件。

而是追加模式點擊功能裏面的DEFS的,你應該只是追加模式與給定的ID ...

var defs = svg.append('defs'); 

defs.append("pattern") 
    .attr("x", 0) 
    .attr("y", 0) 
    .attr("id", "myPattern")//ID here 
    .attr("width", 12) 
    .attr("height", 12) 
    .append("image") 
    .attr("xlink:href", 'https://assets-cdn.github.com/images/modules/open_graph/github-octocat.png') 
    .attr("width", 12) 
    .attr("height", 12) 
    .attr("x", 0) 
    .attr("y", 0); 

...然後,點擊裏面,只是改變了根據該ID圓的填寫:

.on("click", function() { 
    d3.select(this).attr("fill", "url(#myPattern)") 
}) 

這裏是博斯托克的這些變化bl.ocks(我做出的圈更大,所以可以更好地看到圖像):https://bl.ocks.org/anonymous/0e653b6d21c8d57afa234d5d1765efe0/78ba15e533a2b8f8e6575a30d97b27d156ce2faf

+1

赫爾lo Gerardo:非常感謝。您的輸入建議進行以下修改:我爲每個節點添加了一個額外的defs.append(「pattern」)部分,其id與json文件中的id屬性相對應。接下來在鼠標點擊部分我構建了從d.id id,並用作填充。我也增加了半徑。最後,我創建了一個雙擊事件,可以讓所有事情都回來。我使用python創建了index.html文件,以便應對許多部分。一切順利,馬庫斯 – Markus