SVGSVGElement: viewBox 属性

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

SVGSVGElement 接口的只读属性 viewBoxSVGAnimatedRect 对象的形式反映了 SVGSVGElement 元素的 <svg> 属性的 viewBox

该属性描述了 <svg> 元素的 viewBox 属性,该属性用于定义 <svg> 元素的 x 坐标、y 坐标、宽度和高度。SVGAnimatedRect.baseValSVGAnimatedRect.animVal 属性都是 SVGRect 对象,如果 viewBox 未定义,则为 null。这些对象的组件可能与 SVGSVGElement.xSVGSVGElement.ySVGSVGElement.widthSVGSVGElement.height 属性不同,因为 xywidthheight 属性会覆盖 viewBox 属性。

对于非嵌套的 SVG 元素,CSS xywidthheight 属性的值会覆盖任何元素属性,因此由 viewBox 定义的值可能不会反映在元素的显示中。

一个 SVGAnimatedRect 对象。

示例

给出以下 SVG 开头标签

html
<svg viewBox="-12 -18 200 300" x="5" y="5" height="400" width="600"></svg>

我们可以检索 viewBox 的值,但它们与 xywidthheight 属性不同

js
const svg = document.querySelector("svg");
const vBox = svg.viewBox;

// The SVGSVGElement viewBox property
console.dir(vBox); // SVGAnimatedRect { baseVal: SVGRect, animVal: SVGRect }
console.log(vBox.baseVal.x); // -12
console.log(vBox.baseVal.y); // -18
console.log(vBox.baseVal.width); // 200
console.log(vBox.baseVal.height); // 300

// Other SVGSVGElement properties
console.log(svg.x); // 5
console.log(svg.y); // 5
console.log(svg.width); // 400
console.log(svg.height); // 600

规范

规范
Scalable Vector Graphics (SVG) 2
# __svg__SVGFitToViewBox__viewBox

浏览器兼容性

另见