首页 > 解决方案 > 在 a 中使用变量svg中的元素

问题描述

我是 svgs 的新手,必须与他们合作。

因为我对 CSS、SVG 和 JS 基本上一无所知,所以我很难进入这个话题。

我的 SVG-“代码”:

<script  type="text/javascript">
<![CDATA[
  function getCircleX(degrees, radius) {
    if (isNaN(parseFloat(degrees))) {
      degrees=0;
    }
    return Math.cos(degrees*3.14159/180) * radius * (-1);
  }
  function getCircleYup(degrees, radius) {
    if (isNaN(parseFloat(degrees))) {
      degrees=0;
    }
    return Math.sin(degrees*3.14159/180) * radius * (-1);
   }
 function getCircleYdown(degrees, radius) {
    if (isNaN(parseFloat(degrees))) {
      degrees=0;
    }
    return Math.sin(degrees*3.14159/180) * radius;
 }
]]>
</script>

<g>
<path
   id="Path1"
   style="fill:#ff0000;"
   d="M 547.5 161.5 h 17.5 a 17.5 17.5 0 0 1  getCircleX(30,17.5) getCircleYup(30,17.5) z" />
</g>

所以,我知道这行不通,因为我不能在我的 SVG 元素中调用 js 函数。但我该怎么做呢?

非常感谢您的帮助!

标签: javascriptsvg

解决方案


正如您似乎知道的那样,您不能在 HTML 中间直接调用 javascript,因此您需要从 javascript 代码中修改(或创建)svg 元素。这是一个用于在 javascript 中设置路径属性的示例setAttribute(使用模板文字来构建字符串)。

这可能不是做你想做的最好的方法 - 如果你创建的 SVG 是静态的,你应该运行一次 js(可能在浏览器控制台中)以获得你需要的结果。这样,禁用 javascript 的人就可以看到它。

function getCircleX(degrees, radius) {
  if (isNaN(parseFloat(degrees))) {
    degrees=0;
  }
  return Math.cos(degrees*3.14159/180) * radius * (-1);
}
function getCircleYup(degrees, radius) {
  if (isNaN(parseFloat(degrees))) {
    degrees=0;
  }
  return Math.sin(degrees*3.14159/180) * radius * (-1);
}
function getCircleYdown(degrees, radius) {
  if (isNaN(parseFloat(degrees))) {
    degrees=0;
  }
  return Math.sin(degrees*3.14159/180) * radius;
}
path=`M 547.5 161.5 h 17.5 a 17.5 17.5 0 0 1  ${getCircleX(30,17.5)} ${getCircleYup(30,17.5)} z`
document.getElementById("Path1").setAttribute("d",path)
<svg viewBox="500 150 100 20"><g>
<path
   id="Path1"
   style="fill:#ff0000;"
   d="" />
</g></svg>

请注意,svg 元素需要在 js 运行之前存在 - 要么确保 js 在<script>html 中的标记中比 svg 晚,要么将其放在仅在文档加载后运行的函数中。


推荐阅读