问题描述: 当重新进入Angular页面时,使用SVGGraphicsElement.getScreenCTM方法获取SVG元素的平移值时,返回错误的值。
解决方法:
import { Component, AfterViewInit, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-svg-component',
template: `
`,
})
export class SvgComponent implements AfterViewInit {
@ViewChild('svgElement') svgElementRef: ElementRef;
ngAfterViewInit(): void {
this.getSVGElementTranslation();
}
getSVGElementTranslation(): void {
const svgElement = this.svgElementRef.nativeElement;
const gElement = svgElement.querySelector('g'); // Assuming the SVG element is inside a element
if (gElement) {
const ctm = gElement.getScreenCTM();
const translationX = ctm.e;
const translationY = ctm.f;
console.log('Translation X:', translationX);
console.log('Translation Y:', translationY);
}
}
}
import { Component, AfterViewChecked, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-svg-component',
template: `
`,
})
export class SvgComponent implements AfterViewChecked {
@ViewChild('svgElement') svgElementRef: ElementRef;
ngAfterViewChecked(): void {
this.getSVGElementTranslation();
}
getSVGElementTranslation(): void {
const svgElement = this.svgElementRef.nativeElement;
const gElement = svgElement.querySelector('g'); // Assuming the SVG element is inside a element
if (gElement) {
const ctm = gElement.getScreenCTM();
const translationX = ctm.e;
const translationY = ctm.f;
console.log('Translation X:', translationX);
console.log('Translation Y:', translationY);
}
}
}
这两种方法都会在Angular组件初始化完成后,或在Angular渲染周期内检查并获取SVG元素的平移值。根据需要选择适合的生命周期钩子函数。
上一篇:Angular页面显示为空白