【问题标题】:SVG line draw - using the same javascript function for multiple SVGsSVG 线条绘制 - 对多个 SVG 使用相同的 javascript 函数
【发布时间】:2018-04-18 18:20:03
【问题描述】:

我最近进入了使用 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。

希望这是一个简单的解决方法。有人可以帮忙吗?

【问题讨论】:

  • 您发布的内容是否适用于某个元素,还是缺少某些内容?
  • 为什么要发布有效的代码?您的 getElementsByClassName() 想法应该可行。如果不是,则发布 那个 代码。不要忘记添加minimal reproducible example
  • @PaulLeBeau 代码不起作用。这就是为什么我没有在 26 分钟前发布解决方案,例如...显示 = “无”
  • 将 id 作为参数传递给函数,而不是硬编码。
  • 谢谢@RobertLongson

标签: javascript css animation svg getelementbyid


【解决方案1】:

这是一个工作示例:

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');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-03
    • 2018-12-23
    • 2016-11-19
    • 2021-10-17
    相关资源
    最近更新 更多