如何在SVG中以绝对尺寸设置相对位置的元素? [英] How to set an element with relative positioning in absolute dimensions in SVG?

查看:1128
本文介绍了如何在SVG中以绝对尺寸设置相对位置的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Recently began to use SVG in my personal projects. I've learned that SVG is not (just) an image but also a document. I'm willing to know how to set an element with relative positioning in absolute dimensions in SVG?

为了更好地理解问题(如果我没有足够清楚地说明问题),我绘制了一个图表以使其更容易获得图片:

For a better understanding in case I didn't make the question clear enough, I've drawn a diagram to make it easier to get the picture:

就像这张图片一样,我有一个100x100像素尺寸的正方形.希望用户更换阅读设备时,希望粉红色的正方形可以保持其大小和位置.

As in this image, I have a square in 100x100 px dimension. When the user changes his/her reading device, I hope the pink square can keep the size and the positioning.

我已经读过AMELIA BELLAMY的文章"如何缩放SVG ". -CSS Tricks上的ROYDS,有了这个主意,但并没有真正找到实现的方法.

I've read about the article 'How to Scale SVG' by AMELIA BELLAMY-ROYDS on CSS Tricks, got the idea but didn't really find out the way doing it.

我在SVG文件中找到了<rect>标签,但是不知道如何在父容器的比例更改时使粉红色的正方形保持多大的大小.

I've found <rect> tag in SVG file, but have no idea how to make the pink square can be maintained how big it is when the scale of parent container changes.

任何建议或文章,将不胜感激.

Any suggestion, or article, will be appreciated in advance.

推荐答案

最简单的解决方案是不调整SVG的大小.您给SVG设置了宽度和高度(以像素为单位)(或其他值),并且使SVG没有响应.

The easiest solution would be not resizing the SVG. You give your SVG a width and a height in pixels (or whatever) and you make your SVG not responsive.

如果这不适合您,如果您需要调整整个svg元素的大小,而不是粉红色矩形,接下来是一个示例,其中我调整了SVG画布的大小,但<rect>显然是 不调整大小.

If this doesn't work for you, if you need to resize the whole svg element but not the pink rectangle, next comes an example where I resize the SVG canvas but the <rect> is apparently not resized.

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>

这篇关于如何在SVG中以绝对尺寸设置相对位置的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆