How to make a “bent rectangle” in SVG?

前端 未结 2 397
夕颜
夕颜 2021-01-21 04:50

I have a project I am working on that requires me to make a circular navigation with buttons that look like the bars around the Iron Man thing pictured below. I can draw simple

2条回答
  •  盖世英雄少女心
    2021-01-21 05:08

    First I'm creating one segment (path). Then I'm reusing it with use rotating it.

    const SVG_NS = 'http://www.w3.org/2000/svg';
    const SVG_XLINK = "http://www.w3.org/1999/xlink";
    const deg = 180 / Math.PI;
    let R = 50;// the outer radius
    let r = 35;// the inner radius
    let A = 2*Math.PI/7;// the angle for the segment + space
    let a = 2*A/3; // the angle for the segment
    
    
    let path = document.createElementNS(SVG_NS, 'path');
    let p1 = {x:0,y:-R}
    let p2 = {
      x : R*Math.cos(a - Math.PI/2),
      y : R*Math.sin(a - Math.PI/2)
    }
    let p3 = {
      x : r*Math.cos(a - Math.PI/2),
      y : r*Math.sin(a - Math.PI/2)
    }
    let p4 = {
      x : 0,
      y : -r
    }
    let d = `M${p1.x},${p1.y}
             A${R},${R} 0 0,1,${p2.x},${p2.y}
             L${p3.x},${p3.y}
             A${r},${r} 0 0,0,${p4.x},${p4.y}
             L${p1.x},${p1.y}Z
    `;
    path.setAttributeNS(null, "d", d);
    path.setAttributeNS(null, "id", "arc");
    defs.appendChild(path);
    
    
    
    
    for(let i = 0; i < 7; i++){
     let use = document.createElementNS(SVG_NS, 'use');
      use.setAttributeNS(SVG_XLINK, "xlink:href", "#arc")
      use.setAttributeNS(null, "fill", "gold");
      use.setAttributeNS(null, "transform", `rotate(${i*A*deg})`);
      svg.appendChild(use); 
      
    }
    
      
      
      
      
      
      
    

    Or even simpler: this time I'm using stroke-dasharray and I'm calculating the size for the stroke and the gaps

    const SVG_NS = 'http://www.w3.org/2000/svg';
    let R = 40;
    
    let perimeter = 2*Math.PI*R
    let dash = .7*perimeter/7;
    let gap = .3*perimeter/7;
    
    
    let dasharray = document.createElementNS(SVG_NS, 'circle');
    dasharray.setAttributeNS(null, "r", R);
    dasharray.setAttributeNS(null, "stroke-dasharray", `${dash}, ${gap}`);
    
    svg.appendChild(dasharray);
    circle{stroke-width:20px; stroke:black;fill:none;}

提交回复
热议问题