获取SVG元素的宽度/高度

编程入门 行业动态 更新时间:2024-10-28 18:22:07
本文介绍了获取SVG元素的宽度/高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

获取 svg 元素尺寸的正确方法是什么?

jsfiddle/langdonx/Xkv3X/

Chrome 28:

样式x 客户端300x100 抵消300x100

IE 10:

stylex client300x100 offsetundefinedxundefined

FireFox 23:

stylexclient0x0offsetundefinedxundefined

svg1 上有宽度和高度属性,但 .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 300x100

IE 10:

stylex client300x100 offsetundefinedxundefined

FireFox 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元素的宽度/高度

本文发布于:2023-08-02 08:24:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1276190.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:宽度   元素   高度   SVG

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!