在Firefox中获取SVG <img/>的高度/宽度

时间:2017-04-19 15:16:15

标签: javascript google-chrome firefox svg cross-browser

我正在尝试使用image.widthimage.height来获取在JS中创建的SVG元素的高度/宽度。

在Chrome(最新版)上,这会返回宽度和高度,两个base64编码的SVG和数据URI都是image.src

但是,在Firefox(最新版)上,即使我设置了0侦听器,这些都会返回image.onload

实施例

// base64 encoded SVG - EXPECTED 250x150
const base64String = new Image();
base64String.src = "data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4KPCEtLSBHZW5lcmF0b3I6IEFkb2JlIElsbHVzdHJhdG9yIDE5LjIuMSwgU1ZHIEV4cG9ydCBQbHVnLUluIC4gU1ZHIFZlcnNpb246IDYuMDAgQnVpbGQgMCkgIC0tPgo8c3ZnIHZlcnNpb249IjEuMSIgaWQ9IkxheWVyXzEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHg9IjBweCIgeT0iMHB4IgoJIHZpZXdCb3g9IjAgMCA5NS43IDU3LjQiIGVuYWJsZS1iYWNrZ3JvdW5kPSJuZXcgMCAwIDk1LjcgNTcuNCIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIGQ9Ik0yNi44LDE2LjljLTUuOC0wLjEtMTEuMSwyLjMtMTQuOSw2LjJjLTAuMi0xLjQtMC4zLTIuOC0wLjMtNC4yQzExLjgsOC43LDIxLjEsMi4zLDMxLjUsMi41TDI5LjcsMEMxMy40LTAuOCwwLjMsMTIsMCwyOAoJYy0wLjMsMTYsOS4yLDI5LjEsMjUuNiwyOS4zbDAtMC4xYzAuMiwwLDAuMywwLjEsMC40LDAuMWMxMS4yLDAuMiwyMC40LTguNywyMC42LTE5LjlDNDYuOSwyNi4zLDM4LDE3LjEsMjYuOCwxNi45Ii8+CjxwYXRoIGQ9Ik03NS44LDE2LjlDNzAsMTYuOCw2NC43LDE5LjMsNjEsMjMuMmMtMC4yLTEuNC0wLjMtMi44LTAuMy00LjJDNjAuOCw4LjgsNzAuMSwyLjQsODAuNiwyLjZsLTEuOC0yLjQKCUM2Mi40LTAuNyw0OS4zLDEyLjEsNDksMjhjLTAuMywxNiw5LjIsMjkuMSwyNS42LDI5LjNsMC0wLjFjMC4yLDAsMC4zLDAuMSwwLjQsMC4xYzExLjIsMC4yLDIwLjQtOC43LDIwLjYtMTkuOQoJQzk1LjksMjYuNCw4NywxNy4xLDc1LjgsMTYuOSIvPgo8L3N2Zz4K";

base64String.onload = function() {
  console.log(base64String.width, base64String.height); // Returns 250 150 on Chrome, 0 0 on FF
};

here's a JSBin显示问题。在Chrome和FF中打开它以查看不同的输出。那里还有一个.jpg作为控件也适用于两者。

1 个答案:

答案 0 :(得分:1)

经过一些研究后,似乎浏览器在没有尺寸的情况下为SVG提供了一些默认值,同时保留了宽高比,Chrome为350x150。 Firefox会为这些值返回0。 source