11

Данный вопрос инспирирован ответом.
Красный круг находится в левом верхнем углу до начала анимации animateMotion.

Ниже пример кода:

<div id="pathContainer4">
		<button id="btn1" onclick="forwardSVG()">forward</button />
		<button id="btn2" onclick="middleSVG()">Middle</button />
		<button id="btn3" onclick="backSVG()">Back</button />
</div>	
<svg  xmlns="http://www.w3.org/2000/svg" 
    xmlns:xlink="http://www.w3.org/1999/xlink" height="160" width="360" >
  <g fill="none" stroke="black" stroke-width="1">
    <path stroke-dasharray="3" id="motionpath2"
					d="M 10 80 C 40 10, 65 10, 95 80 S 150 150, 180 80" />
  </g>
   <circle class="circle2" r=8 fill=red>
  			         
	 <animateMotion
	   id="forward"
	   dur="2s"
	   begin="indefinite"
	   repeatCount="1"
	   keyPoints="0;1"
	   keyTimes="0;1"
       calcMode="linear"	   >
		 <mpath href="#motionpath2" />
	 </animateMotion> 
		<animateMotion
		   id="middle"
		   dur="2s"
		   begin="indefinite"
		   repeatCount="1"
		   keyPoints="0.5;1"
		   keyTimes="0;1"
		   calcMode="linear"					>
		 <mpath href="#motionpath2" />
	    </animateMotion> 
		   <animateMotion
		   id="back"
		   dur="2s"
		   begin="indefinite"
		   repeatCount="1"
		   keyPoints="1;0"
		   keyTimes="0;1"
		   calcMode="linear"					>
		 <mpath href="#motionpath2" />
	    </animateMotion>
         </circle>
		</svg>
		
<script>
var animation1 = document.getElementById("forward")
function forwardSVG(){
     animation1.beginElement();
} 
var animation2 = document.getElementById("middle")
function middleSVG(){
     animation2.beginElement();
}  

var animation3 = document.getElementById("back")
function backSVG(){
     animation3.beginElement();
}
</script>

Я пытался спрятать красный круг за пределы холста перемещением его влево cx="-18". Но это не помогло, красный круг стал перемещаться во время анимации выше пути.

<div id="pathContainer4">
		<button id="btn1" onclick="forwardSVG()">forward</button >
		<button id="btn2" onclick="middleSVG()">Middle</button >
		<button id="btn3" onclick="backSVG()">Back</button >
</div>	
<svg  xmlns="http://www.w3.org/2000/svg" 
    xmlns:xlink="http://www.w3.org/1999/xlink" height="160" width="360" >
  <g fill="none" stroke="black" stroke-width="1">
    <path stroke-dasharray="3" id="motionpath2"
					d="M 10 80 C 40 10, 65 10, 95 80 S 150 150, 180 80" />
  </g>
   <circle class="circle2" r="8" fill="red" cx="-18">
  			         
	 <animateMotion
	   id="forward"
	   dur="2s"
	   begin="indefinite"
	   repeatCount="1"
	   keyPoints="0;1"
	   keyTimes="0;1"
       calcMode="linear"	   >
		 <mpath href="#motionpath2" />
	 </animateMotion> 
		<animateMotion
		   id="middle"
		   dur="2s"
		   begin="indefinite"
		   repeatCount="1"
		   keyPoints="0.5;1"
		   keyTimes="0;1"
		   calcMode="linear"					>
		 <mpath href="#motionpath2" />
	    </animateMotion> 
		   <animateMotion
		   id="back"
		   dur="2s"
		   begin="indefinite"
		   repeatCount="1"
		   keyPoints="1;0"
		   keyTimes="0;1"
		   calcMode="linear"					>
		 <mpath href="#motionpath2" />
	    </animateMotion>
         </circle>
		</svg>
		
<script>
var animation1 = document.getElementById("forward")
function forwardSVG(){
     animation1.beginElement();
} 
var animation2 = document.getElementById("middle")
function middleSVG(){
     animation2.beginElement();
}  

var animation3 = document.getElementById("back")
function backSVG(){
     animation3.beginElement();
}
</script>

Как добиться исчезновения круга из левого верхнего угла холста SVG до начала анимации?

UPDATE 16.12.2019

Благодарю всех, кто откликнулся на решение фундаментальной проблемы SVG.


Но у каждого решения, на мой взгляд, есть те или иные недочёты:

  • Решения с помощью команд SVG: viewBox, translate имеют ограничения по размерам холста. При других размерах возможна подрезка траектории движения или объекта движения.
  • Решения JS имеют объемный код и вмешиваются в процесс анимации SVG

Смотрите в сторону сокрытия шарика до начала анимации средствами CSS,JS

Код должен быть минимальным по объему и быть универсальным при любых значениях холста SVG.
Принимаются дополнительные ответы в новых постах, от тех участников, которые уже ответили. А также приветствуются новые ответы от новых участников.

4
  • Изначально скрыть CSS-ом, потом function forwardSVG(){ animation1.beginElement(); document.querySelector('.circle2').style.display = 'block'; setTimeout(function() { document.querySelector('.circle2').style.display = 'none'; }, 1950); }
    – br3t
    13 дек 2019 в 15:47
  • @br3t Тут способов очень много и CSS и SVG и JS, я даже знаю некоторые :) Публикуйте полный ответ. Всем, у кого ответ будет на уровне, рабочий гарантированы плюсики, лучшему ответу ещё и зелёная галка :) 13 дек 2019 в 15:52
  • Не сильно ли топорно получается? Тайминг анимации SVG и таймер JS - есть ли гарантия, что они совпадут?
    – br3t
    13 дек 2019 в 16:02
  • @br3t конечно такое решение очень рискованное. Но лучше опубликовать, чем оставлять в комментариях, так как это может остановить других с ответами, типа уже есть решение в комментах Впрочем, всё на ваше усмотрение 13 дек 2019 в 16:06

7 ответов 7

8

в лоб

class SvgAnimation {
  constructor(node) {
    this.node = node;

    if (!this.node) return;

    this.controls = this.node.querySelector('.controls');
    this.svg = this.node.querySelector('svg');

    this.onControlClick = this.onControlClick.bind(this);

    this.controls.addEventListener('click', this.onControlClick, false);
  }

  onControlClick(e) {
    const button = e.target.closest('.btn');

    if (!button) return;

    const animationName = button.getAttribute('data-animation');

    if (!animationName)
      throw new Error('Missing required parameterm data-animation');

    const animationDur = +button.getAttribute('data-duration') || 2;

    if (isNaN(animationDur))
      throw new Error('data-duration property should be number value');

    this.startAnimation(animationName, animationDur);
  }

  startAnimation(animationName, animationDur) {
    const animation = document.querySelector(`[data-animation-name=${animationName}]`);

    if (!animation)
      throw new Error(`Cannot found animation with '${animationName}' name`);

    animation.setAttribute('dur', animationDur + 's');

    this.svg.classList.add('animate');

    animation.beginElement();

    setTimeout(() => {
      this.svg.classList.remove('animate')
    }, animationDur * 1000);
  }
}

const root = document.querySelector('.container');

new SvgAnimation(root);
svg circle {
  opacity: 0;
}

svg.animate circle {
  opacity: 1;
}
<div class="container">
  <div class="controls">
    <button class="btn" data-animation="forward" data-duration="2">forward</button>
    <button class="btn" data-animation="middle" data-duration="2">Middle</button>
    <button class="btn" data-animation="back" data-duration="2">Back</button>
  </div>

  <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" height="160" width="360">
  <g fill="none" stroke="black" stroke-width="1">
    <path stroke-dasharray="3" id="motionpath2"
					d="M 10 80 C 40 10, 65 10, 95 80 S 150 150, 180 80" />
  </g>
   <circle class="circle2" r=8 fill=red>
  			         
	 <animateMotion
	   data-animation-name="forward"
	   begin="indefinite"
	   repeatCount="1"
	   keyPoints="0;1"
	   keyTimes="0;1"
       calcMode="linear"	   >
		 <mpath href="#motionpath2" />
	 </animateMotion> 
		<animateMotion
		   data-animation-name="middle"
		   begin="indefinite"
		   repeatCount="1"
		   keyPoints="0.5;1"
		   keyTimes="0;1"
		   calcMode="linear"					>
		 <mpath href="#motionpath2" />
	    </animateMotion> 
		   <animateMotion
		   data-animation-name="back"
		   begin="indefinite"
		   repeatCount="1"
		   keyPoints="1;0"
		   keyTimes="0;1"
		   calcMode="linear"					>
		 <mpath href="#motionpath2" />
	    </animateMotion>
         </circle>
		</svg>
</div>

4
  • 5
    Я отдаю дань вашему мастерству. Ваши многие ответы мне очень нравятся, но здесь вы явно перемудрили :) Только без обид, хорошо? Просто ваш код вызвал ассоциацию со старым анекдотом. "Когда одному умному человеку сказали, что снаряд летит по параболе, то он воскликнул, - Так можно стрелять из-за угла! Надо только пушку положить на бок! " Решение очень простое, буквально пару строчек кода. Попробуйте взглянуть на задачу с другой стороны. 13 дек 2019 в 20:14
  • C новыми идеями, новый ответ будете делать? См. Update в вопросе. Если да, то подожду ещё несколько дней. 19 дек 2019 в 9:38
  • @Alexandr_TT, добрых времени суток, хотелось бы, да времени не нахожу)
    – meine
    19 дек 2019 в 9:58
  • Здравствуйте Я могу подождать неделю, можно было бы и больше, но Новый год скоро. В принципе, когда, сделаете, тогда и сделаете, хоть в следующем году. Проблема animateMotion общеизвестна, но универсального решения пока я в сети не видел. Каждый решает, кто во что горазд. 19 дек 2019 в 10:18
6

Ещё более костыльное, зато работающее решение: переносим траекторию на 10 пикселей по обеим осям (с кривой это не работает, видно, что черная-новая и оранжевая-старая траектории не идентичны, но вы можете посчитать по формулам, какие значения точек должны быть, я в кривых не силен), лишнее обрезаем CSS-ом.

var animation1 = document.getElementById("forward");
function forwardSVG(){
     animation1.beginElement();
} 
var animation2 = document.getElementById("middle");
function middleSVG(){
     animation2.beginElement();
}  

var animation3 = document.getElementById("back");
function backSVG(){
     animation3.beginElement();
}
.svg-wrapper {
    width:360px;
    height: 160px;
    overflow: hidden;
}
.svg-wrapper svg {
    margin: -10px 0 0 -10px;
}
<div id="pathContainer4">
		<button id="btn1" onclick="forwardSVG()">forward</button>
		<button id="btn2" onclick="middleSVG()">Middle</button>
		<button id="btn3" onclick="backSVG()">Back</button>
</div>
<div class="svg-wrapper">
<svg  xmlns="http://www.w3.org/2000/svg" 
    xmlns:xlink="http://www.w3.org/1999/xlink" height="170" width="370" >
  <g fill="none" stroke="black" stroke-width="1">
    <path stroke-dasharray="3" id="motionpathOriginal"
					d="M 10 80 C 40 10, 65 10, 95 80 S 150 150, 180 80" stroke="orange" />
    <path stroke-dasharray="3" id="motionpath2"
					d="M 20 90 C 50 20, 85 20, 105 90 S 160 160, 190 90" />
  </g>
   <circle class="circle2" r=8 fill=red>
  			         
	 <animateMotion
	   id="forward"
	   dur="2s"
	   begin="indefinite"
	   repeatCount="1"
	   keyPoints="0;1"
	   keyTimes="0;1"
       calcMode="linear"	   >
		 <mpath href="#motionpath2" />
	 </animateMotion> 
		<animateMotion
		   id="middle"
		   dur="2s"
		   begin="indefinite"
		   repeatCount="1"
		   keyPoints="0.5;1"
		   keyTimes="0;1"
		   calcMode="linear"					>
		 <mpath href="#motionpath2" />
	    </animateMotion> 
		   <animateMotion
		   id="back"
		   dur="2s"
		   begin="indefinite"
		   repeatCount="1"
		   keyPoints="1;0"
		   keyTimes="0;1"
		   calcMode="linear"					>
		 <mpath href="#motionpath2" />
	    </animateMotion>
         </circle>
		</svg>
</div>

6
  • интересное решение, свежим ветром подуло :) но очень опасное и не предсказуемое решение 14 дек 2019 в 22:54
  • 2
    @Alexandr_TT Сразу на ум пришла эта картинка i.imgur.com/Q3cUg29.gif
    – br3t
    14 дек 2019 в 22:56
  • Да, в точку! Классная иллюстрирующая гифка 14 дек 2019 в 22:59
  • Новые идеи, новый ответ будете делать? См. Update в вопросе. Если да, то подожду ещё несколько дней. 19 дек 2019 в 9:34
  • @Alexandr_TT Больше ничего в голову не приходит :(
    – br3t
    19 дек 2019 в 12:16
6

Прячем элемент до начала анимации <circle opacity="0" и показываем его после клика на любую из трех кнопок.

circ.style.opacity = "1";  

 var circ =  document.getElementById("circle2");   
var animation1 = document.getElementById("forward");
function forwardSVG(){
      
	 circ.style.opacity = "1";
	 animation1.beginElement();
	
} 
var animation2 = document.getElementById("middle")
function middleSVG(){
     circ.style.opacity = "1";
	 animation2.beginElement();
}  

var animation3 = document.getElementById("back")
function backSVG(){
     circ.style.opacity = "1";
	 animation3.beginElement();
} 
<div id="pathContainer4">
		<button id="btn1" onclick="forwardSVG()">forward</button />
		<button id="btn2" onclick="middleSVG()">Middle</button />
		<button id="btn3" onclick="backSVG()">Back</button />
</div>	
<svg id="svg1"  xmlns="http://www.w3.org/2000/svg" 
    xmlns:xlink="http://www.w3.org/1999/xlink" height="160" width="360" >
  <g fill="none" stroke="black" stroke-width="1">
    <path stroke-dasharray="3" id="motionpath2"
					d="M 10 80 C 40 10, 65 10, 95 80 S 150 150, 180 80" />
  </g>
   <circle id="circle2" r="8" fill="red" opacity="0" >
  	 
	 <animateMotion
	   id="forward"
	   dur="2s"
	   begin="indefinite"
	   repeatCount="1"
	   keyPoints="0;1"
	   keyTimes="0;1"
       calcMode="linear"  >
		 <mpath href="#motionpath2" />
	 </animateMotion> 
		<animateMotion
		   id="middle"
		   dur="2s"
		   begin="indefinite"
		   repeatCount="1"
		   keyPoints="0.5;1"
		   keyTimes="0;1"
		   calcMode="linear" >
		 <mpath href="#motionpath2" />
	    </animateMotion> 
		   <animateMotion
		   id="back"
		   dur="2s"
		   begin="indefinite"
		   repeatCount="1"
		   keyPoints="1;0"
		   keyTimes="0;1"
		   calcMode="linear" >
		 <mpath href="#motionpath2" />
	    </animateMotion>
         </circle>
		</svg>
		

5

В лоб так в лоб:

<div>
    <button onclick="forward.beginElement()">forward</button>
    <button onclick="middle.beginElement()">Middle</button>
    <button onclick="back.beginElement()">Back</button>
</div>	
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" 
    height="160" width="360" viewBox='0 10 360 160' >
    
  <g fill="none" stroke="black" stroke-width="1">
    <path stroke-dasharray="3" id="motionpath2"
          d="M 10 80 C 40 10, 65 10, 95 80 S 150 150, 180 80" />
  </g>
  <circle class="circle2" r=8 fill=red>
  			         
     <animateMotion calcMode="linear"	begin="indefinite" 
       id="forward" dur="2s" repeatCount="1"
       keyPoints="0;1"
       keyTimes="0;1">
         <mpath href="#motionpath2" />
     </animateMotion> 

      <animateMotion calcMode="linear"	begin="indefinite" 
         id="middle" dur="2s" repeatCount="1"
         keyPoints="0.5;1"
         keyTimes="0;1">
           <mpath href="#motionpath2" />
      </animateMotion> 

      <animateMotion calcMode="linear"	begin="indefinite"
         id="back" dur="2s" repeatCount="1"
         keyPoints="1;0"
         keyTimes="0;1">
           <mpath href="#motionpath2" />
       </animateMotion>
   </circle>
</svg>

Не нашли отличий? А теперь внимательно посмотрите на viewBox!

6
  • Да, ты отлично понимаешь SVG -- viewBox='0 10 360 160' - подвинул холст влево на 10px и вуаля! Спрятал шарик Но в этом вопросе я ищу общее решение, когда нельзя двигать холст ни влево ни вверх иначе в других случаях вполне реальна подрезка траектории или объекта движения, как например в этом вопросе 15 дек 2019 в 8:29
  • @Alexandr_TT ну можно еще анимацию атрибута opacity засинхронизировать через begin, но уж больно много кода будет, или scale:0 15 дек 2019 в 8:32
  • @Alexandr_TT только двигал холст я вверх =) 15 дек 2019 в 8:33
  • так я так и сделал, посмотри мой ответ Ну да вверх :) первый параметр viewBox -X, второй Y 15 дек 2019 в 8:34
  • @Alexandr_TT я имел в виду smil анимацию 15 дек 2019 в 8:35
4

Ок, давайте попробуем:

var animation1 = document.getElementById("forward");
function forwardSVG(){
     animation1.beginElement();
     showHideCircle();
} 
var animation2 = document.getElementById("middle");
function middleSVG(){
     animation2.beginElement();
     showHideCircle();
}  

var animation3 = document.getElementById("back");
function backSVG(){
     animation3.beginElement();
     showHideCircle();
}
function showHideCircle() {
     var circle2 = document.querySelector('.circle2');
     circle2.style.fill = 'red';
     setTimeout(function() {
          circle2.style.fill = 'none';
     }, 1950);
}
<div id="pathContainer4">
		<button id="btn1" onclick="forwardSVG()">forward</button>
		<button id="btn2" onclick="middleSVG()">Middle</button>
		<button id="btn3" onclick="backSVG()">Back</button>
</div>	
<svg  xmlns="http://www.w3.org/2000/svg" 
    xmlns:xlink="http://www.w3.org/1999/xlink" height="160" width="360" >
  <g fill="none" stroke="black" stroke-width="1">
    <path stroke-dasharray="3" id="motionpath2"
					d="M 10 80 C 40 10, 65 10, 95 80 S 150 150, 180 80" />
  </g>
   <circle class="circle2" r=8 fill=none>
  			         
	 <animateMotion
	   id="forward"
	   dur="2s"
	   begin="indefinite"
	   repeatCount="1"
	   keyPoints="0;1"
	   keyTimes="0;1"
       calcMode="linear"	   >
		 <mpath href="#motionpath2" />
	 </animateMotion> 
		<animateMotion
		   id="middle"
		   dur="2s"
		   begin="indefinite"
		   repeatCount="1"
		   keyPoints="0.5;1"
		   keyTimes="0;1"
		   calcMode="linear"					>
		 <mpath href="#motionpath2" />
	    </animateMotion> 
		   <animateMotion
		   id="back"
		   dur="2s"
		   begin="indefinite"
		   repeatCount="1"
		   keyPoints="1;0"
		   keyTimes="0;1"
		   calcMode="linear"					>
		 <mpath href="#motionpath2" />
	    </animateMotion>
         </circle>
		</svg>
		
<script>

</script>

1
  • молодец, догадался! Надо просто прятать объект до анимации. Но безопасней не display:none; там могут быть траблы. Лучше fill:none 14 дек 2019 в 22:51
3

translate(X Y)

Это решение для частного случая, когда возможно перемещение с целью скрыть объект движения до начала анимации.

Также этот пример помогает понять некоторые нюансы транcформации SVG

Исходный пример

<div>
    <button onclick="forward.beginElement()">forward</button>
    <button onclick="middle.beginElement()">Middle</button>
    <button onclick="back.beginElement()">Back</button>
</div>	
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" 
    xmlns:xlink="http://www.w3.org/1999/xlink"
	       height="100vh" viewBox="0 0 600 600" > 
 <path  id="pathID" fill="black" stroke="black" stroke-width="1"
    d="M 0.00,250.00
       C 0.00,250.00 33.75,335.50 125.00,375.00
         216.75,415.00 250.00,500.00 250.00,500.00
         250.00,500.00 285.00,408.25 377.25,377.75
         469.50,346.75 500.00,250.00 500.00,250.00
         500.00,250.00 0.00,250.00 0.00,250.00 Z
       M 90.00,308.50" />   
	   <circle id="circle2" cx="0" cy="0" r="15" fill="red"  >  
  	 
	 <animateMotion
	   id="forward"
	   dur="2s"
	   begin="indefinite"
	   repeatCount="1"
	   keyPoints="0;1"
	   keyTimes="0;1"
       calcMode="linear"  >
		 <mpath href="#pathID" />
	 </animateMotion> 
		<animateMotion
		   id="middle"
		   dur="2s"
		   begin="indefinite"
		   repeatCount="1"
		   keyPoints="0.5;1"
		   keyTimes="0;1"
		   calcMode="linear" >
		 <mpath href="#pathID" />
	    </animateMotion> 
		   <animateMotion
		   id="back"
		   dur="2s"
		   begin="indefinite"
		   repeatCount="1"
		   keyPoints="1;0"
		   keyTimes="0;1"
		   calcMode="linear" >
		 <mpath href="#pathID" />
	    </animateMotion>
         </circle>
</svg>

Как видите вверху достаточно места для перемещения основной фигуры.

Двигаем фигуру вверх на 200px transform="translate(0 -200)"

<div>
    <button onclick="forward.beginElement()">forward</button>
    <button onclick="middle.beginElement()">Middle</button>
    <button onclick="back.beginElement()">Back</button>
</div>	
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" 
    xmlns:xlink="http://www.w3.org/1999/xlink"
	       height="100vh" viewBox="0 0 600 600" > 

<path transform="translate(0 -200)" id="pathID" fill="black" stroke="black" stroke-width="1"
    d="M 0.00,250.00
       C 0.00,250.00 33.75,335.50 125.00,375.00
         216.75,415.00 250.00,500.00 250.00,500.00
         250.00,500.00 285.00,408.25 377.25,377.75
         469.50,346.75 500.00,250.00 500.00,250.00
         500.00,250.00 0.00,250.00 0.00,250.00 Z
       M 90.00,308.50" />   
	   <circle id="circle2" cx="0" cy="0" r="15" fill="red" >  
  	 
	 <animateMotion
	   id="forward"
	   dur="2s"
	   begin="indefinite"
	   repeatCount="1"
	   keyPoints="0;1"
	   keyTimes="0;1"
       calcMode="linear"  >
		 <mpath href="#pathID" />
	 </animateMotion> 
		<animateMotion
		   id="middle"
		   dur="2s"
		   begin="indefinite"
		   repeatCount="1"
		   keyPoints="0.5;1"
		   keyTimes="0;1"
		   calcMode="linear" >
		 <mpath href="#pathID" />
	    </animateMotion> 
		   <animateMotion
		   id="back"
		   dur="2s"
		   begin="indefinite"
		   repeatCount="1"
		   keyPoints="1;0"
		   keyTimes="0;1"
		   calcMode="linear" >
		 <mpath href="#pathID" />
	    </animateMotion>
         </circle>
       
</svg>

Фигура поднялась на 200px, но это не затронуло объект движения - красный шарик. Он продолжает двигаться по старой траектории, как будто и не было сдвига траектории.

Корректируем начальное положение красного шарика

<circle id="circle2" cx="0" cy="-200" r="15" fill="red"  >

<div>
    <button onclick="forward.beginElement()">forward</button>
    <button onclick="middle.beginElement()">Middle</button>
    <button onclick="back.beginElement()">Back</button>
</div>	
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" 
    xmlns:xlink="http://www.w3.org/1999/xlink"
	       height="100vh" viewBox="0 0 600 600" > 
 <path transform="translate(0 -200)" id="pathID" fill="black" stroke="black" stroke-width="1"
    d="M 0.00,250.00
       C 0.00,250.00 33.75,335.50 125.00,375.00
         216.75,415.00 250.00,500.00 250.00,500.00
         250.00,500.00 285.00,408.25 377.25,377.75
         469.50,346.75 500.00,250.00 500.00,250.00
         500.00,250.00 0.00,250.00 0.00,250.00 Z
       M 90.00,308.50" />   
	   <circle id="circle2" cx="0" cy="-200" r="15" fill="red"  >  
  	 
	 <animateMotion
	   id="forward"
	   dur="2s"
	   begin="indefinite"
	   repeatCount="1"
	   keyPoints="0;1"
	   keyTimes="0;1"
       calcMode="linear"  >
		 <mpath href="#pathID" />
	 </animateMotion> 
		<animateMotion
		   id="middle"
		   dur="2s"
		   begin="indefinite"
		   repeatCount="1"
		   keyPoints="0.5;1"
		   keyTimes="0;1"
		   calcMode="linear" >
		 <mpath href="#pathID" />
	    </animateMotion> 
		   <animateMotion
		   id="back"
		   dur="2s"
		   begin="indefinite"
		   repeatCount="1"
		   keyPoints="1;0"
		   keyTimes="0;1"
		   calcMode="linear" >
		 <mpath href="#pathID" />
	    </animateMotion>
         </circle>
</svg>

1

Вот еще один приемлемый вариант с opacity, но тут есть один глюк - при запуске новой анимации раньше завершения предыдущей.

<div>
    <button onclick="forward.beginElement()">forward</button>
    <button onclick="middle.beginElement()">Middle</button>
    <button onclick="back.beginElement()">Back</button>
</div>	
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" 
    height="160" width="360" viewBox='0 0 360 160' >
    
  <g fill="none" stroke="black" stroke-width="1">
    <path stroke-dasharray="3" id="motionpath2"
          d="M 10 80 C 40 10, 65 10, 95 80 S 150 150, 180 80" />
  </g>
  <circle class="circle2" r=8 fill=red opacity=0>
         
     <animate id="showhide" 
             attributeName="opacity"
             dur="2s"
             values="0;1;1;1;0"
             keyTimes="0;0.05;0.5;0.95;1" 
             begin="forward.begin;middle.begin;back.begin" />
             
     <animateMotion calcMode="linear"	begin="indefinite" 
       id="forward" dur="2s" repeatCount="1"
       keyPoints="0;1"
       keyTimes="0;1">
         <mpath href="#motionpath2" />
     </animateMotion> 

      <animateMotion calcMode="linear"	begin="indefinite" 
         id="middle" dur="2s" repeatCount="1"
         keyPoints="0.5;1"
         keyTimes="0;1">
           <mpath href="#motionpath2" />
      </animateMotion> 

      <animateMotion calcMode="linear"	begin="indefinite"
         id="back" dur="2s" repeatCount="1"
         keyPoints="1;0"
         keyTimes="0;1">
           <mpath href="#motionpath2" />
       </animateMotion>
   </circle>
</svg>

6
  • да уже намного лучше, глюк почти незаметен, но всё же это не универсальное решение. Каждый раз надо его будет подгонять под конкретную конфигурацию кнопок управления begin="forward.begin;middle.begin;back.begin" /> и согласовывать по времени. Может всё таки JS? 17 дек 2019 в 12:52
  • @Alexandr_TT тогда и анимация должна быть на requestAnimationFrame 17 дек 2019 в 12:53
  • 1
    да, наверное так 17 дек 2019 в 12:54
  • @Alexandr_TT загляни в чат 17 дек 2019 в 13:02
  • Новые идеи, новый ответ будете делать? См. Update в вопросе. Если да, то подожду ещё несколько дней. 19 дек 2019 в 9:36

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.