Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

302
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda