搜索

首页  >  问答  >  正文

将 DIV 元素放置在 SVG 视口内

如何相对于 SVG 元素定位 HTML DIV 元素?

我使用 D3 生成 SVG 图表:

我想在右下角图例旁边添加一个下拉列表。我确实有相应的元素(一个普通的 HTML DIV 元素),但我不知道如何将其正确定位在图表上。

我了解 SVG 元素的定位,但我不知道如何应用类似于 DIV 元素的内容。

除了将其放置在视口之外(例如下面)之外,还有什么想法吗?

P粉803444331P粉803444331524 天前686

全部回复(1)我来回复

  • P粉529581199

    P粉5295811992023-09-08 16:47:49

    查看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>

    回复
    0
  • 取消回复