Reputation: 2543
I 'm trying to port a variation of the following to Angular 7:
https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_svg_scrolldrawing
(TL;DR - SVG from example works, SVG I made doesn't. Confuse)
Currently I have the following Component:
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;
}
}
}
And the HTML for it works with the triangle from the example:
<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>
However, when I add my custom arrow thingie generated in this way it doesn't display anything:
With the following HMTL instead:
<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>
So SVG from the example works, SVG that I generated doesn't get displayed at all. Is it because it's not a closed drawing? Any help is appreciated :)
Upvotes: 1
Views: 3876
Reputation: 2543
Omg I am so stupid. The container had no width and height, so it was displaying, but the window was 0 x 0 and thus couldn't be seen. Everything above works, as long as there are dimensions specified for the 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>
Upvotes: 2