首页 > 解决方案 > 在 Angular 7 中绘制动画 SVG

问题描述

我正在尝试将以下变体移植到 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 根本不会显示。是不是因为不是闭图?任何帮助表示赞赏:)

标签: angularsvgangular7

解决方案


天哪,我太愚蠢了。容器没有宽度和高度,所以它正在显示,但窗口是 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>

推荐阅读