获取svg元素尺寸的正确方法是什么?
http://jsfiddle.net/langdonx/Xkv3X/
Chrome 28:
style x
client 300x100
offset 300x100
Run Code Online (Sandbox Code Playgroud)
IE 10:
stylex
client300x100
offsetundefinedxundefined
Run Code Online (Sandbox Code Playgroud)
FireFox 23:
"style" "x"
"client" "0x0"
"offset" "undefinedxundefined"
Run Code Online (Sandbox Code Playgroud)
有宽度和高度属性svg1,但.width.baseVal.value只有在我设置元素的宽度和高度属性时才设置.
小提琴看起来像这样:
HTML
<svg id="svg1" xmlns="http://www.w3.org/2000/svg" version="1.1">
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="1" fill="red" />
<circle cx="150" cy="50" r="40" stroke="black" stroke-width="1" fill="green" />
<circle cx="250" cy="50" r="40" stroke="black" stroke-width="1" fill="blue" />
</svg>
Run Code Online (Sandbox Code Playgroud)
JS
var svg1 = document.getElementById('svg1');
console.log(svg1);
console.log('style', svg1.style.width + 'x' + svg1.style.height);
console.log('client', svg1.clientWidth + 'x' + svg1.clientHeight);
console.log('offset', …Run Code Online (Sandbox Code Playgroud) 我想在 js+jquery 中创建图片编辑器。第一步,我要求用户提供图片网址。但是当我尝试在 JS 中加载图像数据(生成 base64 图像 uri)时遇到了问题。我在控制台中收到错误:… has beeb blocked by CORS policy: Access-Control-Allow-Origin …. 但我想知道为什么?如果在 html 文件中我创建例如(图像热链接):
<img src="https://static.pexels.com/photos/87293/pexels-photo-87293.jpeg" />
Run Code Online (Sandbox Code Playgroud)
浏览器加载图像没有任何 CORS 问题!这是我的 JS 代码,对于相同的图像抛出 CORS 问题:
function downloadFile(url) {
console.log({url});
var img = new Image();
img.onload = function() {
console.log('ok');
// never execute because cors error
// … make base64 uri with image data needed for further processing
};
img.crossOrigin = "Anonymous";
img.src = url;
}
Run Code Online (Sandbox Code Playgroud)
所以问题是 - 如何强制 JS 加载图像(作为 html-tag 加载它)并将其转换为 base64 url …
它可以在任何地方工作,但不是在IE 11(我尚未测试其他IE版本).
var img = new Image();
img.onload = function(){
alert( 'img: ' + img.width + 'x' + img.height +
' natural: ' + img.naturalWidth + 'x' + img.naturalHeight );
};
img.src = 'http://upload.wikimedia.org/wikipedia/en/b/b5/Boeing-Logo.svg';
Run Code Online (Sandbox Code Playgroud)
的jsfiddle: JSFiddle
结果:
img: 121x30 natural: 121x30 - 真正的浏览器(Chrome,Safari,Firefox,...)
img: 0x0 natural: 0x0 - IE 11
这里有一个类似的问题:在IE上获取图像加载时的图像宽度失败
这些答案中没有一个解决方案适用于svg.
有没有办法在Internet Explorer 11中获取用Image()加载的svg文件的宽度和高度?
注意:我正在寻找一个解决方案,而不必将元素添加到DOM进行测量,因为我想避免任何不必要的重新流/重绘.