动画后删除 SVG 元素

Posted

技术标签:

【中文标题】动画后删除 SVG 元素【英文标题】:Remove an SVG element after animation 【发布时间】:2017-04-26 06:41:41 【问题描述】:

因此,对于我的作业,我有一个网页,我在其中输入一个数字并选择一个形状,所选形状的所选数字数量将出现并通过一组动画。动画结束后,我需要让形状消失。我已经尝试了所有方法,包括使用 remove() 操作,但仍然无法解决这个问题。

这是我的小提琴:https://jsfiddle.net/o6e2yu5b/2/

这是javascript代码:

draw = function() 
  var typed = $('#howmany').val()
  var shape = $('#shape').val()
  var x, y;

  for (var i = 0; i < typed; i++) 
    x = Math.random() * 350
    y = Math.random() * 350
    if (shape == 'a') 
      pattern = paper.circle(25, 25, 25)
    
    if (shape == 'b') 
      pattern = paper.rect(10, 10, 50, 50)
    
    if (shape == 'c') 
      pattern = paper.path('M25,0 L50,50, L0,50 Z')
    

    color_attr = 
        'fill': '#BB7'
    

    position_attr = 
      'transform': 't' + x + ',' + y
    

    pattern.attr(color_attr)
    pattern.animate(position_attr, 2000)
        onComplete:function() 
        this.target.remove();
    
  


setup = function() 
  paper = Raphael('svg1', 400, 400)
  $('button').click(draw)

jQuery(document).ready(setup)

请帮忙!谢谢

【问题讨论】:

【参考方案1】:

您的 onComplete 函数似乎不正确并且不起作用。所以我做了一个新的 setTimeout 函数,它会在动画完成后删除生成的 shape/s。看看这个演示https://jsfiddle.net/o6e2yu5b/3/

setTimeout(function()
  SVG.find("circle").remove();
  SVG.find("rect").remove();
  SVG.find("path").remove();
, 2000);

【讨论】:

以上是关于动画后删除 SVG 元素的主要内容,如果未能解决你的问题,请参考以下文章

如何在动画完成后删除元素?

SVG.js,从使用“use”导入的元素中删除/读取属性“transform”

从 snap svg 组中的相同位置删除和添加元素

jQuery Validate:在提交之前验证后删除元素?

仅Javascript删除SVG元素的阴影过滤器

SVG 动画图案边缘