我正在嘗試將Steelseries集成到一個 Angular 專案中。按照他們的示例,我的代碼如下所示: app.component.html:
<!DOCTYPE html>
<html>
<!-- <body (BeforeRender)="displayCanvas($event)"> -->
<body >
<div>
<canvas id="myCanvas"></canvas>
</div>
<script src="C:\\ProiecteAngular\\Test\\TestDev\\node_modules\\steelseries\\srcdocs\\index.js"></script>
</body>
</html>
<router-outlet></router-outlet>
app.component.ts:
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
import * as steelseries from "steelseries";
import { Compass } from "steelseries";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
// template: `<canvas #myCanvas></canvas>`
})
//export class AppComponent implements AfterViewInit {
export class AppComponent {
title = 'TestDev';
// @ViewChild('myCanvas', { static: true })
// myCanvas: ElementRef<HTMLCanvasElement>;
displayCanvas(event) {
const compass = new Compass(document.querySelector("myCanvas"), {
size: 200
});
}
// public context: CanvasRenderingContext2D;
// ngAfterViewInit(): void {
// this.context = this.myCanvas.nativeElement.getContext('2d');
// const compass = new Compass(document.querySelector("myCanvas"), {
// size: 200
// });
// }
}
使用此代碼,我的網頁上不會顯示任何內容。我的想法是畫布沒有正確呈現。我已經看到這可以使用ViewChild. 我做了一些不成功的測驗(請參閱 .ts 檔案中的注釋代碼)。我錯過了什么或做錯了什么?提前致謝!
uj5u.com熱心網友回復:
首先,您不需要將 index.js 檔案添加到 html。
例子
突擊閃電戰
html
<div>
<canvas id="myCanvas"></canvas>
</div>
腳本
ngOnInit(): void {
const compass = new Compass(document.querySelector('#myCanvas'), {
size: 200,
});
}
uj5u.com熱心網友回復:
- 您不需要 index.html 中的腳本標記。您正在 app.component.ts 檔案中匯入 js。
- 你
document.querySelector在displayCanvas函式中使用。為了使這項作業,你將需要前綴myCanvas與#像的IDdocument.querySelector("#myCanvas"),并添加id="myCanvas"到畫布html標記。(這#myCanvas與標簽中的屬性不同。請參閱此處的作業示例:https : //stackblitz.com/edit/angular-ivy-gol2jx?file=src/app/app.component.html
但是那樣不是 angular 的最佳實踐,因為你不能將它用于多個組件,因為document.querySelector("#myCanvas")在整個 html 檔案中查找 id 并且只使用第一個。為了使它更像 angular,你需要像你已經提到的那樣ViewChild。只需使用const compass = new Compass(this.myCanvas.nativeElement, ... )
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/367291.html
上一篇:想要在angular中設定模板驅動表單的表單組件的值嗎?
下一篇:如何從控制臺避免此錯誤?
