简体   繁体   中英

Angular: write plain JavaScript and get Elements from the HTML template

I'm trying to write a JS game based on 2D canvas inside an angular component. Inside this component I have a separate JS file (so its the 5th file on the component folder) where I want to write the game logic. I want later to be able to use a service to store player's scores and so on. After searching for similar solutions, I came to this:

The base TS file of the component:

import '../game/test.js';
declare var test: any;
 //etc

export class BaseGamesComponent implements OnInit {

 ngOnInit(){
   console.log(test)
 }

The js file:

console.log('js file')

This works, I can see the log (though I get an error saying test is not defined). But what I want to achieve is something like this:

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

In other words, I want to grab elements from the component template (HTML file) and build the game. Is this the correct approach? If not can someone point me the right direction?

Since you are using Angular I'd suggest a bit different approach.

You can create a service dedicated to handle canvas operations and use it in your BaseGamesComponent.

CanvasService:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class CanvasService {
  constructor() { }

  getCanvasContext() {
    var canvas = document.getElementById("canvas") as HTMLCanvasElement;
    return canvas.getContext("2d");
  }

  // you can implement more canvas stuff here
}

BaseGamesComponent:

import { Component, OnInit } from '@angular/core';
import { CanvasService } from './example.service';

// etc

export class BaseGamesComponent implements OnInit {
  constructor(private canvasService: CanvasService) {}

  ngOnInit() {
    const canvasContext = this.canvasService.getCanvasContext();
    console.log(canvasContext);
  }
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM