本文介绍了获取SVG元素的宽度/高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
获取 svg 元素尺寸的正确方法是什么?
jsfiddle/langdonx/Xkv3X/
Chrome 28:
样式x 客户端300x100 抵消300x100IE 10:
stylex client300x100 offsetundefinedxundefinedFireFox 23:
stylexclient0x0offsetundefinedxundefinedsvg1 上有宽度和高度属性,但 .width .baseVal.value 仅在我设置元素的宽度和高度属性时设置。
<小提琴看起来像这样:HTML
< svg id =svg1xmlns =www.w3/2000/svgversion =1.1> < circle cx =50cy =50r =40stroke =blackstroke-width =1fill =red/> < circle cx =150cy =50r =40stroke =blackstroke-width =1fill =green/> < circle cx =250cy =50r =40stroke =blackstroke-width =1fill =blue/> < / svg>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',svg1.offsetWidth +'x'+ svg1.offsetHeight);CSS
#svg1 {宽度:300px; 身高:100px; }解决方案
使用getBBox函数
jsfiddle/Xkv3X/1/
var bBox = svg1.getBBox(); console.log('XxY',bBox.x +'x'+ bBox.y); console.log('size',bBox.width +'x'+ bBox.height);
What is the proper way to get the dimensions of an svg element?
jsfiddle/langdonx/Xkv3X/
Chrome 28:
style x client 300x100 offset 300x100IE 10:
stylex client300x100 offsetundefinedxundefinedFireFox 23:
"style" "x" "client" "0x0" "offset" "undefinedxundefined"There are width and height properties on svg1, but .width.baseVal.value is only set if I set the width and height attributes on the element.
The fiddle looks like this:
HTML
<svg id="svg1" xmlns="www.w3/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>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', svg1.offsetWidth + 'x' + svg1.offsetHeight);CSS
#svg1 { width: 300px; height: 100px; }解决方案
Use getBBox function
jsfiddle/Xkv3X/1/
var bBox = svg1.getBBox(); console.log('XxY', bBox.x + 'x' + bBox.y); console.log('size', bBox.width + 'x' + bBox.height);
更多推荐
获取SVG元素的宽度/高度
发布评论