The es6 object class is not defined

Hey there, I'm currently working on a simple pong game and encountering an issue with passing the player object into drawPlate. It seems to be printing the information correctly, but then I get hit with an Uncaught TypeError exception.

The data prints fine within my draw() method though.

Take a look at my code below:

"use strict";

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x = canvas.width / 2;
var y = canvas.height - 20;
var offX = 5;
var offY = -5;
var radius = 8;

/**
 * This is the constructor of a player object, parameters are the coordinates of x and y
 */
class Player {
    constructor(x, y) {
        this.x = x;
        this.y = y;
        this.moveRight = false;
        this.moveLeft = false;
    }
}

/**
 * Here we add an event listener to see when the user presses a key, and make the plate move.
 */
document.addEventListener("keydown", handleKeyDown, false);
document.addEventListener("keyup", handleKeyUp, false);

function handleKeyDown(event) {
    switch (event.key) {

        case "ArrowRight":
            player1.moveRight = true;
            break;

        case "ArrowLeft":
            player1.moveLeft = true;
            break;

        default:
            return;
    }
}


function handleKeyUp(event) {
    switch (event.key) {
        case "ArrowRight":
            player1.moveRight = false;
            break;

        case "ArrowLeft":
            player1.moveLeft = false;
            break;

        default:
            return;
    }
}

function drawPlate(player1, player2) {
    console.log(player1.x);

    ctx.beginPath();

    if (player1.moveRight == true) {
        player1.x += 7;
    } else if (player1.moveLeft == true) {
        player1.x -= 7;
    }

    ctx.rect(player1.x, player1.y, canvas.width / 7, 8);
    ctx.fillStyle = "blue";
    ctx.fill();
    ctx.closePath();

    ctx.beginPath();
    ctx.rect(player2.x, player2.y, canvas.width / 7, 8);
    ctx.fillStyle = "green";
    ctx.fill();
    ctx.closePath();
}

function drawBall() {
    ctx.beginPath();
    ctx.arc(x, y, radius, 0, 2 * Math.PI);
    ctx.fillStyle = "red";
    ctx.fill();
    ctx.closePath();
}

function draw(player1, player2) {
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    drawBall();

    drawPlate(player1, player2);

    if (x + radius > canvas.width || x - radius < 0) {
        offX = -offX;
    }

    if (y - radius < 0) {
        offY = -offY;
    } else if (y + radius > canvas.height) {
        alert("GAME OVER");
        location.reload();
    }

    x += offX;
    y += offY;

    requestAnimationFrame(draw);
}
var player1 = new Player(canvas.width / 2 - 20, 0);
var player2 = new Player(canvas.width / 2 - 2, canvas.height - 8);
//console.log(player2.x);

draw(player1, player2);

Answer №1

The issue arises when you initially call the draw function with player1 and player2 as arguments, but then later invoke it using requestAnimationFrame(draw), causing those variables not to be passed along (since requestAnimationFrame only sends a timestamp).

In this particular scenario, considering that global variables are being utilized anyways, it would be best to simply eliminate the person1 and person2 parameters from the draw function and consider player1/player2 as global variables.

To address this, all you need to do is modify the draw function as follows:


function draw() {
    // Insert remaining code here
}

Subsequently, you can invoke the function later without passing any arguments:


var player1 = new Player(canvas.width / 2 - 20, 0);
var player2 = new Player(canvas.width / 2 - 2, canvas.height - 8);
draw();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Harnessing the power of two-way data binding in VueJS

I am looking to utilize Vue's two-way data binding to dynamically update the values of amount and total. The price of a given product is fixed. When users modify the amount, the total = amount * total will be automatically calculated. Similarly, users ...

Exploring the location.path in angularjs

Is there a way to use $location.path for redirection in angularjs? I have the configuration below: ngModule.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) { $urlRouterProvider. ...

Dragging objects on a map is done using jQuery and it causes them to bounce

Currently, I am working on implementing the JQuery Draggable feature. My idea is to create a map where I can attach image Divs to it dynamically using Jquery. So far, I have been successful in adding the Divs and making them draggable around the map effici ...

Trigger a JavaScript alert message upon clicking the close button

I have encountered an issue with my current code. When I click on the close (X) button, it should display an error message stored in variable s. Previously, the script was functioning correctly but now it is not showing any alerts when I click on the close ...

When clicking initially, the default input value in an Angular 2 form does not get set

I am currently learning angular2 as a beginner programmer. My goal is to create a form where, upon clicking on an employee, an editable form will appear with the employee's current data. However, I have encountered an issue where clicking on a user f ...

What is the best way to transfer the "user" object from TopBar.js to App.js in my project?

In my project, TopBar.js functions as an AppBar component responsible for handling user authentication. When a user logs in, I receive an object called "user". My goal is to export this "user" object to App.js. If I am successful in exporting it to App.js ...

Utilize AngularJS to Access Global JavaScript Variables

I recently encountered a situation where I needed to incorporate some dynamic functionality into a website I was building. This led me to AngularJS, which I decided to integrate into certain parts of the site rather than the entire thing. Within my JavaSc ...

Utilizing React Native to seamlessly integrate one JavaScript function into another

I am trying to integrate one javascript module into another. I recently downloaded a demo of GiftedMessanger After downloading the GiftedMessanger demo code, I incorporated all its dependencies into my own React Native (ios) project and successfully insta ...

Sinon and Chai combination for testing multiple nested functions

I attempted to load multiple external JavaScript files using JavaScript. I had a separate code for the injection logic. When I loaded one JavaScript file, the test case worked fine. However, when I tried to load multiple JavaScript files, the test case FA ...

sending information back to the controller with get method (ajax, javascript)

I'm currently facing a challenge where I have an event listener waiting for a button to be pressed. Once the button is pressed, the controller method 'update' is called which then triggers the view method 'input' to fetch data from ...

Picking an element that has a dynamic data attribute, but also considering those with a hyphen

Currently, I am developing a function that will select a span element when clicked based on its data attribute and value. Here is the code snippet: function moveFilterElements(event) { if ($(event).hasClass('active')) { var dataAtt ...

How can I determine which component the input is coming from when I have several components of the same type?

After selecting two dates and clicking submit in the daterange picker, a callback function is triggered. I have two separate daterange pickers for SIM dates and Phone dates. How can I differentiate in the callback function when the user submits dates from ...

Are you looking to refresh the Amplify Redirect URL?

Is there a way to update the redirection URI for Amplify signout in the 'aws-exports' file? What steps should be taken to make this change? Can we simply modify the file directly and then execute 'amplify push'? Update After attempti ...

Modifying the name of a file upload in AngularJS

Does anyone know a way to dynamically change the file name in AngularJS? <input type="file" onchange="angular.element(this).scope().filename(this)"> In the filename method, I am attempting to change the file name but the value is not updating. How ...

Making Node.js Wait Until a Function Completes its Execution

Currently, I am using a for-loop in Node.js to run the x() function from the xray package. This function scrapes data from webpages and then writes that data to files. The program works well when scraping around 100 pages, but I need it to handle around 10 ...

Building a dynamic attribute management system with vue and vuetify

In the backend business object, there is a custom attributes data structure that allows clients to add key/value pairs for storing in the database. For instance: Map<String, String> customAttributes; Here's an example of how it would look in th ...

Transfer information between two devices remotely through AJAX

I am in the process of developing a web application that utilizes a mobile phone as a controller, similar to this example: . The concept is quite simple - I just need to transfer text entered on the phone to the computer. There is no need for a database, ...

React Redux causing React Router to display empty pages

In my App.js, the following code is present: const Index = asyncRoute(() => import('~/pages/index')) const Register = asyncRoute(() => import('~/pages/register')) const AddDesign = asyncRoute(() => import('~/pages/add-des ...

What's the best way to loop through each touch event property within the TouchList of a touch event using JavaScript?

I'm struggling to grasp touch events, as nothing seems to be working for me. For testing purposes, I've created a very basic page: HTML: <div id="TOUCHME"> TOUCH ME </div> <div id="OUTPUT"></div> Jav ...

Single-select components in React Native

I am currently working on implementing a simple single selectable item feature, illustrated in the image provided below. https://i.stack.imgur.com/U2rJd.png At this moment, I have set up an array containing my data items and utilized the .map function to ...