【问题标题】:How to set an element with relative positioning in absolute dimensions in SVG?如何在SVG中以绝对尺寸设置具有相对定位的元素?
【发布时间】:2018-11-11 19:52:14
【问题描述】:

最近开始在我的个人项目中使用 SVG。我了解到 SVG 不仅(只是)图像,而且还是文档。我想知道如何在 SVG 中设置具有绝对尺寸相对定位的元素?

为了更好地理解,以防我没有把问题说得足够清楚,我绘制了一个图表以便更容易获得图片:

在这张图片中,我有一个 100x100 像素尺寸的正方形。当用户更换阅读设备时,希望粉色方块能保持大小和定位。

我已经阅读了 AMELIA BELLAMY-ROYDS 关于 CSS Tricks 的文章“How to Scale SVG”,得到了这个想法,但并没有真正找到方法。

我在SVG文件中找到了<rect>标签,但不知道如何让粉红色方块在父容器的比例发生变化时保持多大。

任何建议或文章,将提前表示赞赏。

【问题讨论】:

    标签: css svg


    【解决方案1】:

    最简单的解决方案是不调整 SVG 的大小。你给你的 SVG 一个宽度和一个像素(或其他)的高度,你让你的 SVG 没有响应。

    如果这对您不起作用,如果您需要调整整个 svg 元素而不是粉红色矩形的大小,接下来是我调整 SVG 画布大小但 <rect> 的示例显然 未调整大小。

    function init(){
      let p = {
      x : 1000 * .05,// 5% of the svg width
      y : 500 * .05  // 5% of the svg height
      }
      
      p = getCoords(p);
      
      let size = {
        x:100,
        y:100
      }
      size = getCoords(size);
    
      // resize the rect 
      theRect.setAttributeNS(null,"x",p.x);
      theRect.setAttributeNS(null,"y",p.y);
      theRect.setAttributeNS(null,"width",size.x);
      theRect.setAttributeNS(null,"height",size.y);
    }
    
    
    function getCoords(o){
    var p = svg.createSVGPoint();
    p.x= o.x;
    p.y= o.y;
    p = p.matrixTransform(svg.getScreenCTM().inverse());
    return p
    }
    
    setTimeout(function() {
    		init();
    		addEventListener('resize', init, false);
    }, 15);
    svg{border:1px solid}
    <svg id="svg" viewBox="0 0 1000 500">
      
      <circle fill="gold" cx="500" cy="250" r="200" />
      <rect id="theRect" fill="hotpink" x="5%" y="5%" width="100px" height="100px" />
      
    </svg>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-10
      • 2020-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-21
      • 2019-06-22
      • 1970-01-01
      相关资源
      最近更新 更多