Platzieren Sie DIV-Elemente im SVG-Ansichtsfenster
P粉803444331
P粉803444331 2023-09-07 17:48:48
0
1
645

Wie positioniere ich HTML-DIV-Elemente relativ zu SVG-Elementen?

Ich habe D3 verwendet, um das SVG-Diagramm zu erstellen:

Ich möchte neben der Legende in der unteren rechten Ecke ein Dropdown-Menü hinzufügen. Ich habe zwar das entsprechende Element (ein normales HTML-DIV-Element), weiß aber nicht, wie ich es richtig im Diagramm positionieren soll.

Ich verstehe die Positionierung von SVG-Elementen, weiß aber nicht, wie man so etwas wie ein DIV-Element anwendet.

Irgendwelche Ideen außer der Platzierung außerhalb des Ansichtsfensters (wie unten)?

P粉803444331
P粉803444331

Antworte allen(1)
P粉529581199

查看CSS 位置。您可以创建一个相对定位的 DIV 来保存您的 SVG。然后,您可以在其顶部放置一个绝对定位的 DIV 以容纳 select 元素;您可以使用它的 lefttop 样式将第二个 DIV 放置在任何您想要的位置。

所有内容都放在一起了:

let w = 500;
let h = 300;
let pad = 10;
let xmin = -2 * Math.PI;
let xmax = 2 * Math.PI;
let ymin = -1.1;
let ymax = 1.1;

let svg = d3.select("#graph")
    .append("svg")
    .attr("max-width", `${w}px`)
    .attr("viewBox", [0, 0, w, h]);
    
let x_scale = d3
  .scaleLinear()
  .domain([xmin, xmax])
  .range([pad, w - pad]);
let y_scale = d3
  .scaleLinear()
  .domain([ymin, ymax])
  .range([h - pad, pad]);
let path = d3
  .line()
  .x((d) => x_scale(d[0]))
  .y((d) => y_scale(d[1]));

svg
  .append("g")
  .attr("transform", `translate(0, ${y_scale(0)})`)
  .call(d3.axisBottom(x_scale).tickFormat(d3.format("d")).tickSizeOuter(0));
svg
  .append("g")
  .attr("transform", `translate(${x_scale(0)})`)
  .call(d3.axisLeft(y_scale).ticks(5).tickSizeOuter(0));
  
d3.select('#function')
  .on('change', function() {
    draw_graph(this.value)
  })
  
  
draw_graph('sine')
  

function draw_graph(f_string) {
  svg.select('path.graph').remove()
  let f
  if(f_string == "sine") {
    f = Math.sin;
  }
  else {
    f = Math.cos;
  }
  let pts = d3.range(xmin, xmax, 0.01)
    .map((x) => [x, f(x)]);
  svg
    .append("path")
    .attr('class', 'graph')
    .attr("d", path(pts))
    .attr("fill", "none")
    .attr("stroke", "black")
    .attr("stroke-width", 3);
}
<script src="https://d3js.org/d3.v7.min.js"></script>

<div style="position: relative" id="viz">
  <svg id="graph" width=500 height=300 style="border: solid 2px black"></svg>
  <div style="border: solid 0.5px black; background-color: rgba(255,255,255,0.7); position: absolute; left: 20px; top: 30px">
    <label for="function">function:</label>
    <select name="function" id="function">
      <option value="sine">sine</option>
      <option value="cosine">cosine</option>
    </select>
   </div>
</div>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage