gpt4 book ai didi

javascript - SVG 线条绘制 - 对多个 SVG 使用相同的 javascript 函数

转载 作者:行者123 更新时间:2023-11-28 01:51:39 25 4
gpt4 key购买 nike

我最近进入了混合使用 JS 和 CSS 的 SVG 操作世界。在这里,我有一条 SVG 线作为使用 JavaScript 绘制的路径。

JS:

    function drawRoundel() {
var path = document.getElementById("roundelPath");
var length = path.getTotalLength();
path.style.transition = path.style.WebkitTransition = 'none';
path.style.strokeDasharray = length + ' ' + length;
path.style.strokeDashoffset = length;
path.getBoundingClientRect();
path.style.transition = path.style.WebkitTransition = 'stroke-dashoffset 3s ease-in-out';
path.style.strokeDashoffset = '0';
}

HTML:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 415 415" width="415" height="415">
<path id="roundelPath" stroke-width="22" d="M181.7,265.6l84.8,123.7c-18.1,5.6-37.3,8.7-57.2,8.7c-106,0-191.9-85.9-191.9-191.9c0-45,15.5-86.3,41.4-119.1
l0.2-0.2l128.7,187.4c21.6,27.7,54.6,38.3,89.8,38.3c67.6,0,123.1-55.5,123.1-123.2c-5.8-66.1-45.1-122.7-100.8-152.5l-0.1,0.1
l-85.9,59.9l-0.1,0c-15.1,10.3-25,27.7-25,47.3c0,31.6,25.6,57.3,57.3,57.3c31.6,0,57.3-25.6,57.3-57.3S277.6,87,245.9,87
c-11.8,0-23.1,3.8-32.2,9.9l-0.1,0.1L56.9,206.3"/>
</svg>

这适用于一个 SVG 实例和一个页面上 ID 为“roundelPath”的路径,但是如果我想要多个具有不同 ID 的 SVG 实例怎么办?我尝试使用 getElementsByClassName,但它提示 getTotalLength。

希望这是一个简单的修复。谁能帮忙?

最佳答案

这是一个工作示例:

JS:

    function drawRoundel(id) {
var path = document.getElementById(id);
var length = path.getTotalLength();
path.style.transition = path1.style.WebkitTransition = 'none';
path.style.strokeDasharray = length + ' ' + length;
path.style.strokeDashoffset = length;
path.getBoundingClientRect();
path.style.transition = path.style.WebkitTransition = 'stroke-dashoffset 3s ease-in-out';
path.style.strokeDashoffset = '0';
}

调用不同id的函数:

drawRoundel('roundelPath1');

drawRoundel('roundelPath2');

关于javascript - SVG 线条绘制 - 对多个 SVG 使用相同的 javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49895631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com