Tips on interpreting a JavaScript page prior to another

function moveCharacter() {
    ctx.clearRect(0, 0, canvas.width, canvas.height)

    let position = Math.floor(gameFrame/staggerFrame) % spriteAnimation[playerState].loc.length
    let frameX = spriteWidth * position
    let frameY = spriteAnimation[playerState].loc[position].y

    ctx.drawImage(playerImage, frameX, frameY, spriteWidth, spriteHeight, playerPositionX, playerPositionY, 150, 150)
    gameFrame++
    //playerImage.style.zIndex = "1"
    requestAnimationFrame(moveCharacter)
}
moveCharacter()

In order to organize my canvas project, I have split it into three separate JavaScript files. The "bg.js" file handles the background element and should be positioned at the back of the canvas. On the other hand, the "enemies.js" file deals with the enemies and needs to be displayed in front of the page to avoid being hidden behind the background. Let me know if you require additional code snippets.

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="Style.css">
    <script src="script.js" defer></script>
    <script src="bg.js" defer></script>
    <script src="enemies.js" defer></script>
    <title>Game</title>
</head>
<body>
    <canvas id="canvas"></canvas>
</body>
</html>

function animateBackground(){
    ctx.clearRect(0, 0, canvas.width, canvas.height)
    allLayers.forEach(object =>  {
        object.update(),
        object.draw()
    })

    requestAnimationFrame(animateBackground)
}
animateBackground()

Answer №1

It's generally acceptable to spread out your code across multiple JavaScript source files. However, issues can arise when conflicting actions occur, as is the case with two actions in your situation.

The functions animateBG and animatePlayer both interact with a shared HTML <canvas> element - for example, clearing it and drawing on it. Additionally, each function has its own requestAnimationFrame(). These actions are not synchronized, leading to possible overlaps where the background may overlap the player or vice versa.

To address this, remove the separate

ctx.clearRect(0, 0, canvas.width, canvas.height)
and requestAnimationFrame() calls within these functions. Instead, create a centralized function that updates the game's visuals. This new function can be stored in a separate .js file.

For example:

background.js

function animateBG(){
    allLayers.forEach(object =>  {
        object.update(),
        object.draw()
    });
}

player.js

function animatePlayer() {
    let position = Math.floor(gameFrame/staggerFrame) % spriteAnimation[playerState].loc.length
    let frameX = spriteWidth * position
    let frameY = spriteAnimation[playerState].loc[position].y

    ctx.drawImage(playerImage, frameX, frameY, spriteWidth, spriteHeight, playerPositionX, playerPositionY, 150, 150)
    gameFrame++
}

newUpdate.js

function update()
{
     ctx.clearRect(0, 0, canvas.width, canvas.height);
     animateBG();
     animatePlayer();
}
requestAnimationFrame(update);

This new update() function first clears the canvas, then draws the background, and finally the player.

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

Vue Router Guard Failing to Work Properly After Page Reload

I have implemented a router guard to protect certain pages in my app. The goal is for users to be prompted to log in when attempting to access these protected pages. Currently, the guard works as expected within the app itself. However, if a user refresh ...

What is the reason for encodeURIComponent not encoding single quotes or apostrophes?

Although the escape() function was deprecated and replaced by encodeURIComponent, there is an issue with encodeURIComponent as it doesn't encode the single quote/apostrophe character. This poses a problem when trying to escape apostrophes in someone&a ...

Add a trash can or delete icon within every row of a table using Vue.js

I am new to vue.js and I'm struggling to implement a trash icon in each row of a table for deleting rows. Additionally, I'm trying to make the input of a cell act as a dropdown menu or list within the table rows. I recently came across this scrip ...

Converting JSON data to JavaScript using AJAX and PHP

Utilizing JavaScript coupled with AJAX enables the display of additional information when a user chooses a 'deal_name' from the dropdown menu using the showPartnerInfo function. The following excerpt from the k1.php file is pertinent: function s ...

Receiving JSON in a C# web service: A step-by-step guide

I created a JSON string using jQuery and now I want to send it to a C# web API controller. Here is an example of the JSON object: {"Name":"","Type":"4","Meals":["2","3"],"Excludes":["Beef","Chicken"]} I attempted to send it with a URL structure like thi ...

What is preventing me from passing str.indexOf into the map function in JavaScript?

How come I'm unable to perform the following action? let str = "A string containing * and ^ as well as $"; let indices = ["*", "^", "$"].map(str.indexOf); // not functional I prefer not to introduce another function that duplicates the functionality ...

Utilizing Ajax to send a parameter to a separate PHP script

I have a dilemma that I need help with. Currently, I have a table displaying data using PHP and SQL in the following format: What I want to achieve is to be able to click a button, retrieve the ID value, and based on that, execute another SQL query to dis ...

Is there a way to update the value of a variable with the help of a checkbox?

When I check the checkbox, the specOrder const gets updated as expected. However, I am struggling to figure out how to remove the value when the checkbox is unchecked. Below is the code I have been working on: const SpecialtyBurgers = () => { cons ...

Why is the responseText from XMLHttpRequest always stripped of tags in AJAX?

Whenever the server sends the XML string to the client using the XMLHttpRequest object, I noticed that when I insert the text inside the div tags, it appears without any tags. However, I actually need the XML tags to be present so that I can parse the cont ...

Can you explain the distinction between using a mouse to click on an input versus selecting it with the tab key?

I have a unique input field that I'm working with: <div class="btn-group btn-xs" dropdown> <input id="simple-btn-keyboard-nav" ng-model="available_fields_query" id="single-button" dropdown-toggle ng-disabled="disabled" placeholder="Add New ...

Adjusting Grid Posts to a Consistent Size (Featuring Photo Posts with Captions Below)

I'm attempting to adjust the size of posts in grid mode on Tumblr. I've discovered that I can modify the width of each post using CSS. However, I'm struggling to locate where I can set the height of a grid post to a specific size. For inst ...

The response from the MySQL insert is not being received by the Ajax request

Currently, I am facing an issue with retrieving the return message after successfully inserting data into a MySQL database via AJAX. I have ensured that the data is being inserted correctly and I am using the latest versions of jQuery and PHP. The code sn ...

Is it necessary for the changeState to be reverted when initiating an UNDO_ONE action to reverse an optimistic delete in @ngrx/data?

Check out the code on StackBlitz When performing an optimistic delete using @ngrx/data, such as removing our Hero "Ant-Man," it impacts the changeState in the following way: { "entityCache": { "Hero": { "ids": [1, 2, 3, 5, 6], "entities ...

Tips for making objects rotate vertically on their axis and orbit around another object in three.js

Thank you in advance for all the support as I've been asking a lot of questions about my project. My project involves creating a simulation where a planet earth and moon rotate around a sun. (They're not exactly rotating around the sun, but more ...

divide an array into two separate arrays depending on whether the index position is odd or even

Here is an example array: Arr1 = [1,1,2,2,3,8,4,6]. I'm trying to divide this array into two new arrays based on the odd or even position of elements. Can anyone provide a solution? New Array 1 (odd positions): [1,2,3,4] New Array 2 (even positions) ...

Sorting alphanumeric strings in React Bootstrap Table Next on a dynamic table

I am facing an issue with sorting columns in a dynamic table with over 70 columns using React-Bootstrap-Table-Next. The problem arises when trying to sort the columns in alphanumerical order, as some columns contain numbers and others contain letters. The ...

Activate Bootstrap modal using an anchor tag that links to a valid external URL as a fallback option

To ensure accessibility for users who may have javascript disabled, we follow a company standard of developing our web pages accordingly. Our target demographic still includes those familiar with VCRs blinking 12:00. One particular challenge involves a te ...

Converting a string to an array in React when updating the state

Currently, I am working on a React CRUD app that allows me to manage dishes. I can add new dishes, display a list of existing ones, update the details of a dish, or delete a dish. My main challenge at the moment is updating the ingredients of a dish. Whil ...

The issue with Mongoose populate failing to populate

I'm facing an issue with populating my users' car inventory. Each car has a userId attached to it upon creation, but for some reason, the population process isn't working as expected, and no errors are being displayed. Let's take a loo ...

Converting an object to JSON in javascript: A step-by-step guide

I have been attempting to convert my object person into a JSON format. const person = new Object(); person.firstName = 'testFirstName'; person.lastName = 'testLastName'; var myJson = JSON.stringify(person); ...