JavaScript 获取 SVG 宽高终极指南
JavaScript 获取 SVG 宽高终极指南
想要用 JavaScript 获取 SVG 图像的宽度和高度?很简单!使用 getBoundingClientRect() 方法可以轻松实现。该方法返回一个包含元素尺寸和位置信息的 DOMRect 对象。
以下是获取 SVG 宽高的分步指南:
-
获取 SVG 元素: 使用
getElementById()或其他 DOM 方法选择你的 SVG 元素。javascript const svgElement = document.getElementById('mySvg'); -
使用
getBoundingClientRect(): 调用 SVG 元素上的getBoundingClientRect()方法。这将返回一个包含width和height属性的对象。javascript const svgRect = svgElement.getBoundingClientRect(); -
提取宽度和高度: 从
svgRect对象中访问width和height属性。 ```javascript const width = svgRect.width; const height = svgRect.height;console.log('宽度:' + width); console.log('高度:' + height); ```
**示例代码:**javascript// 获取 SVG 元素const svg = document.getElementById('mySvg');
// 获取边界框信息const bbox = svg.getBoundingClientRect();
// 提取宽度和高度const width = bbox.width;const height = bbox.height;
console.log('宽度:' + width); console.log('高度:' + height);
注意:
width和height属性返回 SVG 元素的实际渲染尺寸,即使没有在 SVG 文件中明确指定width和height属性。* 如果 SVG 元素没有渲染或隐藏,width和height可能返回 0。
希望本指南能帮助你轻松获取 SVG 图像的宽度和高度!
原文地址: https://www.cveoy.top/t/topic/lalP 著作权归作者所有。请勿转载和采集!