在 Angular 7 中绘制动画 SVG

Draw animated SVG in Angular 7

我正在尝试将以下内容的变体移植到 Angular 7:

https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_svg_scrolldrawing

(TL;DR - 来自示例作品的 SVG,我制作的 SVG 没有。混淆)

目前我有以下组件:

import { Component, OnInit, HostListener, ElementRef, Renderer2, ViewChild } from '@angular/core';

@Component({
  selector: 'svg-component',
  templateUrl: './svg.component.html',
  styleUrls: ['./svg.component.css'],
})

export class SvgComponent implements OnInit {

  @ViewChild('svgElement') svgElement;

  constructor(private el: ElementRef) {}

  @HostListener('window:scroll', ['$event'])
    checkScroll() {
      let componentPosition = this.el.nativeElement.offsetTop;
      let scrollPosition = window.pageYOffset;

      let svgLength = this.svgArrow.nativeElement.getTotalLength();
      this.svgArrow.nativeElement.style.strokeDasharray = arrowLength;
      this.svgArrow.nativeElement.style.strokeDashoffset = arrowLength;

      let scrollPercent: number;

      if (scrollPosition >= componentPosition) {
        // This isn't actually a percentage - in the example they're using a variable between 0 and 1.
        scrollPercent =  (((scrollPosition - componentPosition) / svgLength));

        let draw = svgLength * scrollPercent;
        this.svgArrow.nativeElement.style.strokeDashoffset = svgLength - draw;
      }
    }

}

并且 HTML 因为它适用于示例中的三角形:

<svg>
  <path #svgArrow fill="none" stroke="red" stroke-width="3" id="triangle" d="M150 0 L75 200 L225 200 Z" />
  Sorry, your browser does not support inline SVG.
</svg>

但是,当我添加以这种方式生成的自定义箭头时,它没有显示任何内容:

改为使用以下 HMTL:

<svg>
  <svg #svgArrow stroke="black" stroke-width="3" id="arrow" d="M 400 100 C 350 150 450 125 400 175 C 350 225 450 225 400 300 C 350 350 450 350 400 475 Q 390 450 375 450 Q 380 490 400 525 Q 420 490 425 450" />
  Browser doesn't support inline SVG?
</svg>

示例中的 SVG 有效,我生成的 SVG 根本没有显示。是因为不是封闭图吗?感谢您的帮助:)

我的天啊,我太蠢了。容器没有宽度和高度,所以它正在显示,但是 window 是 0 x 0 因此看不到。只要有为 SVG 指定的尺寸,上面的一切都有效:

<svg height="600px" width="600px">
  <path #svgArrow fill="none" stroke="red" stroke-width="3" id="triangle" d="M150 0 L75 200 L225 200 Z" />
  Sorry, your browser does not support inline SVG.
</svg>