使用 JavaScript 操作 SVG viewbox(无库)

Manipulate SVG viewbox with JavaScript (no libraries)

本文关键字:无库 viewbox SVG JavaScript 操作 使用      更新时间:2023-09-26

我正在尝试在JavaScript中更改SVG元素视图框。基本上,我正在绘制一个二叉搜索树,当它变得太宽时,我想更改视图框以缩小,以便树适合窗口。我目前正在使用:

if(SVGWidth>=1000){
  var a = document.getElementById('svgArea');
  a.setAttribute("viewbox","0 0 " + SVGWidth + " 300");
}

该 HTML 是:

<svg id="svgArea" xmlns="w3.org/2000/svg"; xmlns:xlink="w3.org/1999/xlink"; width="1000" height="300" viewBox="0 0 1000 300">

我也尝试过使用 setAttributeNS('null',...),但这似乎也不起作用。我注意到的一件奇怪的事情是,当我发出警报(a)时,它会给出[对象SVGSVGElement],这似乎很奇怪。任何帮助,不胜感激。

很高兴看到 svg 的上下文,但以下内容对我使用纯 SVG 文档有用:

shape = document.getElementsByTagName("svg")[0];
shape.setAttribute("viewBox", "-250 -250 500 750"); 

也许是因为viewBox区分大小写?

您的代码中有一个错误:"viewbox"与"viewBox"不同...B 为大写。将代码更改为:

a.setAttribute("viewBox","0 0 " + SVGWidth + " 300");

我有一个非常相似的用例,其中调整SVG的大小对于响应式设计至关重要。

const windowWidth = window.innerWidth ||
  document.documentElement.clientWidth ||
  document.body.clientWidth;
const windowHeight = window.innerHeight ||
  document.documentElement.clientHeight ||
  document.body.clientHeight;
// used getElementById for specific SVG
const shape = document.getElementById("background-svg");
function onWindowResize(){
console.log(windowWidth, windowHeight);
if (windowWidth < 600 || windowHeight < 900) {
  shape.setAttribute("viewBox", "0 0 400 800");
}
// Added an Event Listener
window.addEventListener("resize", onWindowResize);

这种方法对我来说效果很好,我希望有改进的余地,很乐意找到替代解决方案。祝您编码愉快!

此外,如果要动态设置视图框维度,请使用 ES6 模板文本而不是字符串串联。

shape = document.getElementsByTagName("svg")[0];
const view = `${xValue} ${yValue} ${width} ${height}`; // template literals
shape.setAttribute("viewBox", view);