簡體   English   中英

如何使用 D3 js(v3) 中的循環在 SVG 元素中創建可變數量的圖像或圓形元素

[英]How to create variable number of image or circle elements in an SVG element using a loop in D3 js(v3)

我正在嘗試使用 d3 制作象形圖。 所以,我有一個范圍從 1 到 10 的縮放值,我想創建圖像或圓圈來表示數字,即數字 7 的 7 個圓圈或圖像,數字 5 的 5 等。圖像或圓圈標簽應該在“mousein”事件上繪制。 'mouseout' 事件不應刪除圖像。 但是每個 mousein 事件都應該重新繪制正確數量的圓圈。 有人可以用正確的方法演示一個簡單的例子嗎?

我嘗試過的事情:我能夠將 append n 圖像標簽添加到 svg 元素,但我只能刪除最后一個元素,因為變量獲取了繪制的最后一個圓圈的值。

for(i=1;i<limit;i++){         // 1<=limit<=10 --> Scaled value on each mousein event
    var img = svg.append("image")
      .attr("x", i*width*1/8)
      .attr("y", height*1/10)
      .style("opacity", 1)
      .attr("width", 50)
      .attr("height", 50)
      .attr("xlink:href", "image.png")
      .attr("class", "image");    
    }

當我將所有元素放在一個組中時,圖像沒有顯示,但元素存在於 DOM 中,並且還顯示了圖像的正確路徑。

D3.js 的全部功能在於它能夠將數據綁定到顯示元素,因此您不必編寫循環來手動將項目添加到 DOM。

此示例演示如何使用在 Mike Bostock 的文章Thinking in Joins中描述的selectAll()data()enter()remove()函數向 SVG 元素添加圓圈。

 const width = 500; const height = 500; let svg = d3.select('svg') // create the rectangles to hover over let rectangleHolders = svg.select('.rectangle-holder').selectAll('rect').data([1, 2, 3, 4, 5]).enter() // to add a rectangle with text, we need to add a group to hold both elements.append('g') // translate group to correct position.attr('transform', (d, i) => `translate(${i*40})`) // add rectangle to each group rectangleHolders.append('rect').attr('height', 18).attr('width', 18) // add event handler to rectangle to draw circles.on('mouseover', draw) // add text to each group rectangleHolders.append('text').attr('dy','15').attr('dx','10').attr('text-anchor','middle').text(d => d) // function to draw circles function draw(number) { console.log('draw', number) // create some dummy data in this case an // array of length 'count' full of nulls const data = Array(number) // select circle elements and bind data let circles = svg.select('.circle-holder').selectAll('circle').data(data) // enter, append and set attributes circles.enter().append('circle').attr('cx', (d, i) => i * 20 + 10).attr('cy', 10).attr('r', 8).attr('value', d => d) // add a tranisition to the opacity so the circles fade in.attr('opacity', 0).transition().attr('opacity', 1) // exit and remove unused elements (with transition) circles.exit().transition().attr('opacity', 0).remove() }
 rect { fill: none; stroke: black; } body { font-family:sans-serif; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script> <svg height="40" width="200"> <g class="rectangle-holder"></g> <g class="circle-holder" transform="translate(0,20)"></g> </svg>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM