Maximizing HTML5 Game Performance through requestAnimationFrame Refresh Rate

I am currently working on a HTML5 Canvas and JavaScript game. Initially, the frames per second (fps) are decent, but as the game progresses, the fps starts decreasing. It usually starts at around 45 fps and drops to only 5 fps.

Here is my current game loop:

var last_draw = Date.now(); //Keeps track of when GameDraw was last called
var fps;
function gameloop()
{
    var elapsed = Date.now() - last_draw;
    last_draw = Date.now()
    fps = 1000 / elapsed;
    context.clearRect(0, 0, canvas.height, canvas.width); //Clears the canvas
    GameUpdate();// Update properties of game elements
    GameDraw(); //Draw all visible elements in the canvas
    window.requestAnimationFrame(gameloop); //Request next frame
}

window.requestAnimationFrame(gameloop); 

I have tested this game in the following browsers:

  1. Mozilla Firefox 32.0.3
  2. Google Chrome 38.0.2125.101 m

My questions are:

  1. Why does requestAnimationFrame (rAF) call less frequently as the game progresses?
  2. Could it be due to a memory leak?
  3. Is high execution time for GameDraw and GameUpdate causing this issue?
  4. Is the time taken to execute GameDraw function different from the actual time it takes to draw elements on the canvas? The GameDraw function calls the draw function for each game element.

Answer №1

Many resources are available online to help with optimizing canvas performance. It's not just about which functions you use, but rather the amount of processing happening between each frame.

Your question(s) may not have a single answer, so I will briefly touch on each sub-question:

Why is requestAnimationFrame calling less frequently as the game progresses?

As mentioned in the following question, there could be a memory leak causing this issue. This could be due to adding more textures, event listeners, DOM objects, or simply too many JS objects accumulating without being cleared by the Garbage Collector. You need to identify what is changing or increasing between frames.

Could this be caused by a Memory leak?

It's highly likely, and easy to test. In Chrome, press Shift+Escape to open the task manager and monitor memory, CPU usage for each tab.

Is the high time taken by GameDraw and GameUpdate contributing to this issue?

Absolutely! This can also lead to memory leaks. Profiling the CPU and canvas can provide valuable insights. Enable canvas profiling in Chrome from configuration flags to investigate where the majority of lag is coming from.

Does the time it takes to execute Gamedraw function differ from the time taken to draw elements on the canvas?

In most cases, both processes are sequential (blocking codes), meaning one follows the other. The time to render a frame is typically the sum of both processes. Effective canvas rendering optimization can greatly improve performance in this regard.

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

What is the best approach to extracting tightly-coupled code and converting it into an external library?

I have a question regarding paradigms that I would like to address, and if this is not the appropriate platform, please guide me to the right place. Your recommendations are most welcome :) Currently, I am tasked with extracting a significant piece of fun ...

Optimizing the management of optional post fields in an Express.js application

When creating an endpoint with Express that includes both mandatory and non-mandatory fields in the post request, what is the optimal strategy for handling this? Would it be best to use something like if (field exists in req.body) { set variable } else { ...

Utilizing an array in a PHP URL and incorporating it into JavaScript operations

In this PHP file, I am working on validating only numeric input for text-boxes with the ids "Mobile" and "Home": $elementids = array("Mobile","Home"); $serialized = rawurlencode(serialize($elementids)); $testvar='validate-nums.php?elementids='. ...

The jQuery form validator doesn't seem to work with AJAX for me, but I've figured out how to make jQuery validate without using

I have been facing an issue with my code that involves the jquery validator and ajax. The code seems to validate properly and the serialize() function appears to be working as I can see the data in the browser. However, the problem arises when the data d ...

Tips for utilizing the select feature within an ng-repeat loop while maintaining the selected value when fetching data from an API

I am currently facing an issue with using select inside ng-repeat. I am attempting to correctly map the value coming from my API to the select as the selected value. However, I seem to be missing something from my end. Can someone please help me identify a ...

The use of '-' in v-bind:style within Vue.js

I'm having trouble figuring out how to use CSS code with dashes in v-bind:style. When I attempt something like this: <DIV style="width:100px;height: 100px;background-color: red;cursor: pointer;" v-bind:style="{ margin-left: margin + 'px' ...

AngularJS - Utilizing Google's Place Autocomplete API Key

Recently, I started digging into Google's APIs and attempting to integrate the Places Autocomplete API with Angular. Although I'm fairly new to autocomplete features in general, I haven't included the jQuery library in my project yet. I&apos ...

Strip excess white space from a complex string using Javascript

I have the following sets of strings: 14/04/22 10:45:20 12.08N 87.65W 15.0 2.9ML Frente a Corinto 14/04/21 11:05:34 12.10N 87.70W 140.0 3.5MC Cerca de Masachapa 14/04/22 09:00:09 12.35N 86.44W 12.4 1.3ML Cerca del volcan Momotombo 14/04/21 23:33:37 1 ...

Generating an HTML table using an array retrieved from a PHP execute_db function, displaying repeated entries

My goal is to dynamically populate an HTML table with data retrieved from a SQL query. The structure of the table, including headings, should adjust based on user selections, reflecting the results of the query. While searching for a solution, I came acros ...

Challenges Encountered with AngularJS $http Service

How do I pass my data from the http request to the $scope in the MainCtrl? The code below should fetch data from a MySQL Database with an $http-service, but somehow the data provided by the service doesn't go to the controller or gets displayed incor ...

Ensure that the sidebar automatically scrolls to the bottom once the main content has reached the bottom

I am facing an issue with a sticky sidebar that has a fixed height of calc(100vh-90px) and the main content. The sidebar contains dynamic content, which may exceed its defined height, resulting in a scrollbar. On the other hand, the main content is lengthy ...

Develop a voice recording feature using ReactJS

In my quest to enhance a chat application with voice recording functionality, I came across the react-mic package. It worked smoothly and provided me with the data needed at the end of the recording session. (link: https://i.stack.imgur.com/nhNCq.png) Now ...

Supervising the organization of HTML sections for an offline web application

Currently, I am developing an offline HTML5 application that involves a significant amount of DOM manipulation through the creation of HTML strings within JavaScript functions. For example: var html=''; html+='<div class="main">&apos ...

Problem with AngularJS factory causing issues with promises

I have a factory in AngularJS set up like this: 'use strict'; angular.module('frontRplApp') .factory('paymentService', function ($rootScope, $http, config, tools) { var urlBase = config.baseUrl; var payme ...

JS Data error: The attributes provided must include the property indicated by idAttribute - particularly with regards to hasMany relationships

Encountered Error: The main key for my user model is username. The primary key for my routes is the routename. When my API returns JSONs, they are nested inside data:{} following jsonapi.org specifications. However, this structure differs from what js-dat ...

CSS Hover Effects on Navigation Bar Not Displaying as Expected

I was aiming to make one of my Navbar tabs stand out by having a different appearance compared to the others. However, there seems to be an issue with the text color for this particular tab in the hover state - it works inconsistently across different brow ...

Having trouble with Npx and npm commands not running in the VSCode terminal?

I am currently facing an issue while attempting to set up a react app in vscode using the command npx create-react-app my-app. It seems like the command is not working properly. Can anyone provide guidance on what steps I should take next? Despite watchin ...

Remove the Prisma self-referencing relationship (one-to-many)

I'm working with this particular prisma schema: model Directory { id String @id @default(cuid()) name String? parentDirectoryId String? userId String parentDirectory Directory? @relation("p ...

Utilize MetroUiCSS to effortlessly integrate a sleek calendar into your AngularJS application

I'm looking to incorporate a calendar from Metro Ui CSS into my project. Here is the link to the calendar: However, I am struggling with how to activate the calendar. I have already included all necessary scripts in my index.html (3 scripts) and have ...

Guide to tallying the occurrences of a specific key within an object array and attaching the count to each key's current value

Is there a way to determine the number of occurrences of the 'value' key within an object that is part of an array, and then add the count to each value if applicable? In this case, 'a' represents the original data var a = [ { id: ...