Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

303
Visualizações
Uncaught TypeError: this.canvas is undefined

I'm trying to create an instance of the Object class but i get this error:
Uncaught TypeError: this.canvas is undefined

I'm quite new to javascript, so I might have made a few silly mistakes.

Here is the code and the folder structure:

projectname/
- index.html
- index.js
- js/
-- Object.js

file: index.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>title</title>
    </head>
    <body>
        <div id="container"></div>
        <script src="index.js" type="module"></script>
    </body>
</html>

file: index.js

import { Object } from "/js/Object.js";

var obj = new Object();
obj.position = (500, 500, 0);

file: /js/Object.js

export class Object {

    constructor() {
        this.position = new Array(0, 0, 0);
        this.velocity = new Array(0, 0, 0);
        this.force = new Array(0, 0, 0);
        this.mass = 0;

        this.canvas = document.createElement("canvas");
    }

    get position() {
        return this._position;
    }

    set position(n_position) {
        this._position = n_position;
        this.canvas.style.left = n_position[0].toString()+"px";
        this.canvas.style.top = n_position[1].toString()+"px";
    }
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Inside your constructor you have:

this.position = new Array(0, 0, 0);

which calls the setter function which tries to read this.canvas before you have:

this.canvas = document.createElement("canvas");

which creates the canvas that you tried to modify five lines earlier.


Order matters. Create your canvas before you try to modify it.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda