angular - 在 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 根本不会显示。是不是因为不是闭图?任何帮助表示赞赏:)
解决方案
天哪,我太愚蠢了。容器没有宽度和高度,所以它正在显示,但窗口是 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>
推荐阅读
- wordpress - 如何将下一页链接更改为自定义链接
- reactjs - Github 搜索未使用配置文件填充页面
- python - Pandas 根据其他列标准插入缺失值
- swift - 登录和注销时如何更新购物车数量?迅速
- google-chrome - 如何在不禁用 GPU 的情况下修复 Google Chrome 空白主屏幕错误?
- perl - 如何使用 Perl LWP 指定 SSL CipherString?
- javascript - “React Js”中的水平网站滚动
- unity3d - 如何在 URP 中勾勒(剪影)3D 模型?
- python - 如何在kivy python中让任何应用程序在后台运行
- objective-c - 在 Objective-C 项目中的 Swift 文件中使用 Objective-C Singleton