【问题标题】:Do we gain anything from setting the SVG elements width and height to 100%?将 SVG 元素的宽度和高度设置为 100%,我们有什么收获吗?
【发布时间】:2020-02-08 08:35:22
【问题描述】:

Angular 材质文档应用程序有一个 SVG 查看器可以执行以下操作:

  inlineSvgContent(template) {
    this.elementRef.nativeElement.innerHTML = template;

    if (this.scaleToContainer) {
      let svg = this.elementRef.nativeElement.querySelector('svg');
      svg.setAttribute('width', '100%');
      svg.setAttribute('height', '100%');
      svg.setAttribute('preserveAspectRatio', 'xMidYMid meet');
    }
  }

IIUC 使 SVG 缩放到容器所需要做的就是使用正确的 viewBox 参数 as explained here 保存它。

这是来自答案的演示圈:

  <svg viewBox="0 0 100 100">
    <circle cx="50" cy="50" r="40" fill="gold"/>
    <rect x="10" y="50" width="20" height="50" fill="gold"/>
    <rect x="70" y="50" width="20" height="50" fill="gold"/>
    <circle cx="35" cy="45" r="5"/>
    <circle cx="65" cy="45" r="5"/>
  </svg>

该圆圈将适合任何容器,无需设置width=100%height=100%

所以我假设 Angular 团队这样做的原因是因为想将 widthheight 设置为另一个用例的某个固定值?

一般来说,我只是对设计以及我们是否从中受益感到好奇。换句话说,这是 UX 开发人员的常见模式吗?为什么?

【问题讨论】:

  • 这将是为了响应。见这篇文章:webdesign.tutsplus.com/tutorials/…
  • 即:We’ll start by looking at “zooming”, which we can do with the last two viewBox parameters: width and height respectively. We’ll leave the first two parameters at 0 0 for now. If those last two parameters have the same dimensions as the viewport, there’s no zooming in or out so nothing changes.

标签: javascript html css angular svg


【解决方案1】:

在这种情况下,它可能很有用,因为该方法似乎不知道如何声明 svg 元素,因此它们覆盖了这些属性,以便之前设置的任何内容都不会阻止元素的响应性.

由于这个函数被命名为inlineSvgContent,我们可以假设它是一种消毒剂。

使独立的 svg 图像具有绝对宽度和高度属性(例如以 px 为单位)是很常见的(甚至推荐),以便渲染器知道如何绘制它。如果不这样做,默认值为 100%,但在某些情况下,很难理解 100% 到底是什么。具有绝对宽度和高度允许众所周知的纵横比。


现在,如果您要从头开始创建元素,那将毫无用处,因为这些实际上是默认值:

const svg = document.createElementNS( 'http://www.w3.org/2000/svg', 'svg' );

console.log( 'width', svg.width.baseVal.valueAsString ); // 100%
console.log( 'height', svg.height.baseVal.valueAsString ); // 100%
console.log( 'preserveAspectRatio', svg.preserveAspectRatio.baseVal );
// align: 6 => SVG_PRESERVEASPECTRATIO_XMIDYMID
// meetOrSlice: 1 => SVG_MEETORSLICE_MEET
// => "xMidYMid meet"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-16
    • 1970-01-01
    • 2018-02-26
    • 2017-01-27
    • 1970-01-01
    • 1970-01-01
    • 2013-08-11
    相关资源
    最近更新 更多