javascript - 在 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 函数。但我该怎么做呢?
非常感谢您的帮助!
解决方案
正如您似乎知道的那样,您不能在 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 晚,要么将其放在仅在文档加载后运行的函数中。
推荐阅读
- android - 添加库后显示此错误在路径上找不到类“.MainActivity”:DexPathList
- c# - 有没有办法编写一个 for 循环,这样它就不会在序列中递增?
- php - woocommerce:付款完成后如何将从远程服务器获取的数据添加到项目中?
- java - 具有超级方法调用的继承方法的切入点
- python - 在用于数据块的 spark-submit 的主 python 文件中导入其他 python 文件
- java - 如何使用两个包实现观察者模式
- javascript - 如何从缓冲区呈现数据?反应原生 Javascript
- reactjs - redux-presist 不更新浏览器的本地存储
- java - 使用连接 XML 文件连接到 oracle 数据库?
- docker - 可以在 Kubernetes pod 中托管两个 Web 服务吗?