Initial loading issue with HTML5 Canvas in Android WebView

As I work on developing a HTML5 canvas-based game within a WebView of an existing application, I encounter a puzzling issue. Upon the initial run of the game, everything seems to be in order - logs indicate that it's ready and running, yet nothing is displayed within the WebView. Oddly enough, if I switch to something else in the WebView and then return to the game, it suddenly loads and renders without any problems. What could be causing this strange behavior of the canvas not displaying on the first run but working fine on subsequent reloads?

Here are some more details:

  • No console errors pop up when the game is loaded for the first time.
  • The game runs smoothly in the iOS version of the app.
  • The CSS styling applied to the canvas element does not render initially, indicating that it's not an issue with loading assets before display.

All my past issues stemmed from trying to render assets prematurely, which were resolved once cached images were displayed upon subsequent reloads. However, I can't seem to pinpoint why the canvas fails to display at all specifically on Android.

This is the HTML code being loaded into the WebView:

<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, minimum-scale=1, initial-scale=1, user-scalable=yes">
  <title>Darts</title>
  <meta name="description" content="Darts GamePad Game">
  <script src="js/dummy-gamepad-functions.js"></script>
  <script src="js/libs/polyfill.js"></script>
  <script src="js/gamepad-client.js"></script>
  <script src="js/darts-boot.js"></script>
  <script src="js/darts-loader.js"></script>
  <link rel="stylesheet" href="css/darts.css">
</head>

<body onload=bootGame()>
  <div id="darts-game-container"></div>
</body>

</html>

Below is the script used for the onload function:

var bootGame = () => {

  //create canvas element
  let canvas = document.createElement('canvas');
  canvas.id = "darts-canvas";
  canvas.width = 740;
  canvas.height = 400;

  let gameContainer = document.getElementById("darts-game-container");
  gameContainer.appendChild(canvas);

  //scale canvas to view window
  let gamepadViewport = document.getElementById("darts-game-container"),
    gamepadCanvas = document.getElementById("darts-canvas"),
    viewportWidth = window.innerWidth,
    canvasWidth = gamepadCanvas.width,
    viewportHeight = window.innerHeight,
    canvasHeight = gamepadCanvas.height;

  let scaleRatio = Math.min(viewportWidth/canvasWidth, viewportHeight/canvasHeight);
  if (scaleRatio < 1) {
    gamepadViewport.style.transform = `scale(${scaleRatio}, ${scaleRatio})`;
    gamepadViewport.style.webkitTransform = `scale(${scaleRatio}, ${scaleRatio})`;
    gamepadViewport.style.mozTransform = `scale(${scaleRatio}, ${scaleRatio})`;
    gamepadViewport.style.oTransform = `scale(${scaleRatio}, ${scaleRatio})`;
  }

  //initialize Loader
  Darts.Loader = new Loader();

  //initialize GamePad API, then initialize core classes when loaded
  GamePadClient = new GamePadClient();
  GamePadClient.initialize()
    .then(() => {

      //load all scripts
      return Darts.Loader.loadScripts(LIBS_TO_LOAD, COMMON_LIB_PATH, LIB_NAME_SUFFIX)
    })
    .then(() => {
      return Darts.Loader.loadScripts(SCRIPTS_TO_LOAD, COMMON_SCRIPT_PATH, SCRIPT_NAME_SUFFIX)
    })
    .then(() => {
      //initialize core classes
      Darts.Controller = new Controller();
      Darts.Logic = new Logic();
      Darts.Display = new Display();
      Darts.GameProps = new GameProps();
      Darts.GameState = new GameState();

      //loads display elements and scripts, then initializes game once complete
      Darts.Controller.initGame();
    });

}

Answer №1

After some investigation, I discovered that the key to resolving the issue lied in my approach to resizing the canvas. It turned out that window.innerWidth and window.innerHeight remained unset when window.onload was triggered, starting with a default value of 0. However, these values were only accurately defined after the window.onresize event occurred. Therefore, by monitoring this event and subsequently adjusting the canvas size, I was able to achieve the desired outcome.

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 causing the div to not update until the for loop is completed?

I have an HTML page where I am trying to update a div while a for loop is running. However, the div does not update until after the loop finishes. Why is this happening? <!DOCTYPE html> <html> <body> ...

The statusText variable for getXMLHTTP object is not found when the status is not equal to

Earlier, I posted about this issue before isolating the problem. Now that I have isolated it, I wanted to repost with a clearer focus on the two functions causing the problem. Whenever I update my State, it triggers the getCity function. The call is being ...

Exploration of jQuery Dropdown Menus

Encountering a problem with my dropdown menu. Check out the code here: http://jsfiddle.net/xY2p6/1/ It seems like a simple issue that I can't figure out, but as shown in the link, the functionality is not working properly. I need help linking the hid ...

Implementing CSS keyframes when a specified PHP condition is satisfied

I am looking to implement an opening animation on my website that should only play when a user visits the site for the first time. I want to avoid displaying the animation every time the page is reloaded, so it should only run if a cookie indicating the us ...

Adjust the width of a DIV based on the content of other DIVs, and float and center them all

Initially, what seemed like a simple task has turned out to be more complicated than I anticipated. Here is my code: <html> <head> <style> div { border-top: 1px solid black; margin: 10px; } div#all { border: 0; } </style> <body ...

Is it the right time to dive into HTML5 & CSS3?

The excitement around HTML5 and CSS3 is hard to ignore. But when is the right time to start incorporating them into our projects? How close are we to fully utilizing their capabilities? Update: I'm not interested in following the principles of: Grac ...

Windows and MacOS each use unique methods for displaying linear gradients

Check out this code snippet featuring a background gradient background: rgba(0,0,0,0) linear-gradient(rgb(245, 245, 245),rgba(0,0,0,0)) repeat scroll 0 0; This code renders correctly on Windows (chrome, ie, firefox) https://i.stack.imgur.com/XU2gW ...

Tips for placing a large image within a small div

I have an image with a ratio of 1920*1300 that I want to be displayed on any device the website is viewed and cover the entire div. Check out my code below: .carousel { width: 100vw; height: 80vh; position: relative; } .carousel a { width: 1 ...

Tips on how to position a expanding textarea in line with buttons

I need assistance with aligning a textarea that is growing to the left, and action buttons positioned on the right side of the textarea. My goal is to have the action buttons aligned at the bottom, level with the expanding text area. Here is the code snip ...

Authenticate through Twitter when using PhoneGap Cordova

Looking to implement Twitter login in my application using JavaScript and HTML. How can I redirect users to the Twitter login page when they click on the "Sign In with Twitter" button? ...

Select a random class from an array of classes in JavaScript

I have a collection of Classes: possibleEnemies: [ Slime, (currently only one available) ], I am trying to randomly pick one of them and assign it to a variable like this (all classes are derived from the Enemy class): this.enemy = new this.possibleEn ...

Only IE7 seems to be experiencing a z-index problem with CSS that is not present on any

I’ve encountered a perplexing problem with CSS z-index in IE7 that I just can’t seem to solve. #screen { display: none; background-image: url('/images/bg.png'); background-repeat: repeat; position: fixed; top: 0px; le ...

Another component's Angular event emitter is causing confusion with that of a different component

INTRODUCTION In my project, I have created two components: image-input-single and a test container. The image-input-single component is a "dumb" component that simplifies the process of selecting an image, compressing it, and retrieving its URL. The Type ...

Different parameters in an Angular filter pipe

Currently, I am facing a challenge in implementing multiple filters on a pipe for a search result page that retrieves data from an API. How can I integrate different parameters into this filter pipe successfully? Access the application here: https://stack ...

What are some ways to create a one-sided design without being limited by container constraints

How can I create a block on my site where there are no container restrictions on the right, but they are limited on the left? The goal is to have an image pressed against the right edge of the page while keeping the container limits on the left. Here is my ...

When I zoom in, h4 and h5 headers expand and extend beyond their boundaries

Currently, I am working on designing forms for this specific website. Everything appears to render properly at normal zoom levels. However, when I adjust the zoom in or out slightly, issues arise where the h4's and h5's are no longer centered wit ...

Tips for keeping your button fixed in place

I am encountering an issue where my button moves below the select dropdown list when I try to make a selection. Is there a way to keep the button in place even when the dropdown list from the select box is visible? For reference, here is the current outp ...

What could be causing my slider to malfunction?

No errors are being returned by the console. Currently utilizing Unslider. The setup includes: <div class="slider"> <ul> <li><img src="img/one.jpg" alt=""></li> <li><img src="img/one.jpg" ...

Event object not being passed to function in UIWebView Javascript onclick event

When inserting HTML dynamically using simple NSStrings and then loading it into a UIWebview, the following approach is taken: [NSString stringWithFormat:@"<div onclick=\"MyClickEvent(e);\"....some more text here"> A function is defined li ...

Could you provide some advice for creating a Single Page website?

I am working on a simple HTML setup with various elements such as a navbar and content blocks. <html> <head> <title>My HTML5 App</title> <meta charset="UTF-8"> <meta name="viewport" content="wid ...