I am trying to integrate steelseries in an Angular project. Following their example , my code looks like this: 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
// });
// }
}
With this code, nothing is displayed on my web page. My thought is that canvas is not rendered correctly. I have seen that this could be done using ViewChild
. I did some unsuccessfully tests (see the commented code from.ts file). What am I missing or doing wrong? Thanks in advance!
First of all, you don't need to add index.js file to html.
example
html
<div>
<canvas id="myCanvas"></canvas>
</div>
script
ngOnInit(): void {
const compass = new Compass(document.querySelector('#myCanvas'), {
size: 200,
});
}
document.querySelector
in the displayCanvas
function. To make that work you would need to prefix myCanvas
with #
for the id like document.querySelector("#myCanvas")
and add id="myCanvas"
to the canvas html tag. (That is not the same as just #myCanvas
as attribute in the tag. See an working example here: https://stackblitz.com/edit/angular-ivy-gol2jx?file=src/app/app.component.html document.querySelector("#myCanvas")
looks for the id in the whole html document and uses only the first. To make it more 'angular-like' you would need as you already mentioned ViewChild
. Just use const compass = new Compass(this.myCanvas.nativeElement, ... )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.