笔触动画,如何为显示的笔触附加其他路径? [英] Stroke animation, how to attach another path to the appearing stroke?

查看:86
本文介绍了笔触动画,如何为显示的笔触附加其他路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下动画:

@keyframes dash {
 to {
    stroke-dashoffset: 0;
  }
}


#currency-chart-path {
  stroke-dasharray: 1000;
  stroke-dashoffset: 1000;
  animation: dash 30s linear forwards;
}

<svg id="city-total-v2" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 1000 1000" enable-background="new 0 0 1000 1000" xml:space="preserve">
<g id="Chartline">
  <path id="currency-chart-path" stroke="#7C0A67" stroke-width="3px" fill="none" d="M443,439 L464,435 487,421 511,416 532,424 552,408 572,414 591,413 606,419" />
	<path id="chart-arrow" fill="#7C0A67" d="M604.4,423.5l6.88-2.26l-2.44-3.3c-0.1-0.22-0.25-0.41-0.43-0.58l0.01,0.02l-0.02-0.02
		c0,0,0,0.01,0.01,0.01l-2.48-3.36l-0.08,0.42l-0.27,1.66l-0.03-0.01l-0.68,3.8l0.09,0.04L604.4,423.5z"/>
</g>
</svg>

运行代码段以查看动画。

我想将箭头附加到笔触上,使其看起来像遵循路径。

I want to attach the arrow to the stroke so it look like following the path.

那怎么可能?

推荐答案

是的,但是有可能在这种情况下,您将需要JavaScript。

Yes, it's possible, however in this case you will need JavaScript. Please reed the comments in my code.

let chart = document.querySelector("#currency_chart_path");
// the length of the chart path
let length = currency_chart_path.getTotalLength();
// the request animatioon id
let rid = null;
// setting the stroke-dasharray and the stroke-dashoffset for the chart
chart.style.strokeDasharray = length;
chart.style.strokeDashoffset = length;
// the animation frames
let frames = length;
// two points on the path: the actual point and an other point very near used to calculate the angle of rotation for the arrow
let point1, point2;
// the animation:
function Frame() {
  rid = requestAnimationFrame(Frame);
  chart.style.strokeDashoffset = frames;
  //two points on the path: the actual point and an other point very near
  point1 = chart.getPointAtLength(length - frames);
  point2 = chart.getPointAtLength((length - frames + 2) % length);
  //the angle of rotation for the arrow
  angle = Math.atan2(point2.y - point1.y, point2.x - point1.x);
  // set the transformation for the arrow
  arrow.setAttribute(
    "transform",
    "translate(" +
      [point1.x, point1.y] +
      ")" +
      "rotate(" +
      angle * 180 / Math.PI +
      ")"
  );

  frames--;
  // stop the animation
  if (frames <= 2) {
    cancelAnimationFrame(rid);
    rid = null;
  }
}

Frame();

svg{border:1px solid}

<svg id="city-total-v2" viewBox="400 370 250 100" >
<g id="Chartline">
<path id="currency_chart_path" stroke="#7C0A67" stroke-width="3px" fill="none" d="M443,439 L464,435 487,421 511,416 532,424 552,408 572,414 591,413 606,419" />
<path id="arrow" fill="#7C0A67" d="M0,0L0,-5L7,0L0,5"/>
</g>
</svg>

将SVG与CSS3和HTML5结合使用:用于网页设计的矢量图形

这篇关于笔触动画,如何为显示的笔触附加其他路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆