My HTML, JS, and Canvas project is experiencing issues with displaying images from my JS scripts

I'm attempting to animate 3 boats using JavaScript within a Canvas element. However, I've encountered a problem with my project where the startGame function isn't displaying the images I've selected. Strangely, it only seems to work with the Pic/boat.jpg image that serves as the background. Both my teacher and classmates are stumped by this issue, and despite trying various solutions, none have resolved the problem for me. I'm hoping someone here can provide some assistance:

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

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" media="screen" href="MainC/C.css" />
    <!-- 
    <script src="main.js"></script> -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
        crossorigin="anonymous">
    <style>
        header {
            background-color: rgb(28, 72, 88);
            width: 100%;
            min-height: 100px;
            opacity: 0.7;
            position: fixed;
            background-image: url(pic/VORIcon.png);
        }

        body,
        html {
            height: 100%;
            margin: 0%;
            background-repeat: no-repeat;
            background-size: cover;
        }

        canvas {
            border: 1px solid #d3d3d3;
            background-color: #f1f1f1;
        }
    </style>

</head>

<body background="Pic/boat.jpg" onload="startGame()">
    <header>
        <div class="dropdown">
            <button onclick="myFunction()" class="dropbtn">Menu</button>
            <div id="myDropdown" class="dropdown-content">
                <a href="#News">News</a>
                <a href="#OCRLive">Live Race</a>
            </div>
        </div>

    </header>
    <br>
    <br>
    <br>
    <br>
    <br>




    <script>
        /* When the user clicks on the button, 
        toggle between hiding and showing the dropdown content */
        function myFunction() {
            document.getElementById("myDropdown").classList.toggle("show");
        }

        // Close the dropdown if the user clicks outside of it
        window.onclick = function (event) {
            if (!event.target.matches('.dropbtn')) {

                var dropdowns = document.getElementsByClassName("dropdown-content");
                var i;
                for (i = 0; i < dropdowns.length; i++) {
                    var openDropdown = dropdowns[i];
                    if (openDropdown.classList.contains('show')) {
                        openDropdown.classList.remove('show');
                    }
                }
            }
        }
    </script>

    <script>

        var myGamePiece1;
        var myGamePiece2;
        var myGamePiece3;
        var myGamePiece4;

        function startGame() {
            myGameArea.start();
            myGamePiece1 = new component(30, 30, "Pic/Boat.jpg", 10, 30, "image");
            myGamePiece2 = new component(30, 30, "Pic/Boat.jpg", 10, 110, "image");
            myGamePiece3 = new component(30, 30, "Pic/Boat.jpg", 10, 190, "image");
        }

        var myGameArea = {
            canvas: document.createElement("canvas"),
            start: function () {
                this.canvas.width = 480;
                this.canvas.height = 270;
                this.context = this.canvas.getContext("2d");
                document.body.insertBefore(this.canvas, document.body.childNodes[0]);
            }
        }

        function component(width, height, color, x, y, type) {
            this.type = type;
            if (type == "image") {
                this.image = new Image();
                this.image.src = color;
            }
            this.width = width;
            this.height = height;
            this.x = x;
            this.y = y;
            this.update = function () {
                ctx = myGameArea.context;
                if (type == "image") {
                    ctx.drawImage(this.image,
                        this.x,
                        this.y,
                        this.width, this.height);
                } else {
                    ctx.fillStyle = color;
                    ctx.fillRect(this.x, this.y, this.width, this.height);
                }
            }

        }
        function updateGameArea() {
            myGamePiece1.update();
            myGamePiece2.update();
            myGamePiece3.update();
        }

    </script>


</body>

</html>

If you need further information or clarification, please let me know. I appreciate any help!

PS: Any picture other than the background won't display correctly for me.

CSS:

.dropbtn {
    background-color: #3498DB;
    color: white;
    padding: 16px;
    min-width: 160px;
    font-size: 16px;
    border: none;
    cursor: pointer;
}

.dropbtn:hover, .dropbtn:focus {
    background-color: #2980B9;
}

.dropdown {
    float: right;
    position: relative;
    display: inline-block;
}

.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f1f1f1;
    min-width: 160px;
    overflow: auto;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    right: 0;
    z-index: 1;
}

.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
}

.dropdown a:hover {background-color: #ddd;}

.show {display: block;}

Answer №1

Here is a suggestion: Instead of dynamically creating the canvas element with JavaScript, consider adding it directly to your HTML code. You can remove the inline script and script tags, uncomment the script source tag in your header, and place it just below where the canvas element is defined.

<canvas></canvas>
<script src="main.js"></script>

This change might fix any issues related to the timing of when the script runs and when the canvas is created. It's possible that the script doesn't find the canvas element if it hasn't been created yet.

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

How can I remove the border of an image hyperlink using CSS?

Let's consider the following situation: I have defined the CSS rule a { color: Red } When using Internet Explorer, if I have: <a href="..."> <img src='...' /> </a> it results in a red border around the image. How can ...

Can you please tell me the CSS pseudo element that corresponds to the AM/PM field in an <input type="time">

The issue with the am/pm display is dependent on the browser that the app is opened in. I am looking for a universal solution to ensure it does not appear in any popular browsers. Below is the HTML code for my input time field: <input type="time" for ...

Issue with displaying Modal in ReactJS using hooks

I am currently utilizing react hook and react portal to create and display a modal. Here is the code snippet: Modal.tsx const modalRoot = document.getElementById('modal'); const Modal: React.FC<Props> = memo(({isOpen, toggle, children}) = ...

Get the String from a Formatted Message

Seeking guidance on extracting and exporting the string part from FormattedMessage, specifically for CSV usage. Below is the snippet of my FormattedMessage code (IntlMessages.js): import React from 'react'; import {FormattedMessage, injectIntl} ...

Unable to scroll the control-sidebar in the AdminLTE dashboard

Currently working on a project using adminlte v3.1.0 and encountered an issue with the control-sidebar. After adding the class layout-fixed to the body tag, I'm unable to scroll the sidebar. I would like to have the sidebar fixed but still be able to ...

Utilize Python Selenium to interact with Cookie-Consent pop-ups

Attempting to scrape a webpage using Python and selenium, but encountering difficulty when trying to click the "OK" Button for cookie consent as it cannot be located: View Picture of Consent Dialog Visit Website Here This locator works: driver.find_eleme ...

Experiencing difficulties with writing data to a JSON file in Discord.js after retrieving information from it

Currently, I am in the process of working on a project for a discord server owned by a friend. The goal is to create a 'database' of sorts for our members, including tracking warnings (or strikes), ages (to address issues with underage members), ...

AngularJS modal directives trigger a reset of $scope variables

I am developing a custom AngularJS application that needs to handle and store all the checkbox selections made by the user in a simple array of IDs. The functionality includes displaying a modal when the open button is clicked, allowing the user to perform ...

Step-by-step guide on clipping a path from an image and adjusting the brightness of the remaining unclipped area

Struggling to use clip-path to create a QR code scanner effect on an image. I've tried multiple approaches but can't seem to get it right. Here's what I'm aiming for: https://i.stack.imgur.com/UFcLQ.png I want to clip a square shape f ...

Eliminate the curved edges from the <select> tag

Is there a way to eliminate the rounded corners on a select element? I attempted using the code below, but it resulted in removing the arrows and cutting off the bottom of the placeholder text: select { -webkit-appearance: none; -webkit-border-radius ...

Launching shuttles using HTML and JavaScript

I've been working on an HTML code with JavaScript for a platform validation project. Over the last couple of weeks, I've been diligently coding and testing to ensure everything runs smoothly. However, my code suddenly stopped responding, leaving ...

Modify the item in an array using values from a different item in the same array

Within my code, I am juggling two arrays. The first contains multiple objects, while the second stores serialized form data mapped to JSON. Both arrays share identical keys. My goal is to dynamically update the values of an object in the original array ba ...

Placing an object to the right side

I'm currently developing an app using React Native and I need to position something on the right side of the screen. <View style={searchDrop}> <TextInput style={textInput} placeholder="Search Coin ...

Speed up - Handle alias resolution with module federation

Currently import federation from '@originjs/vite-plugin-federation'; import react from '@vitejs/plugin-react-swc'; import dns from 'dns'; import path from 'path'; import { visualizer } from 'rollup-plugin-visual ...

Encountering an SSL error while trying to establish a connection between a local server and the Heroku PostgreSQL

Currently, I am facing an issue with connecting to my postgreSQL database on Heroku from my express app. The connection functions properly when the express app is deployed on Heroku, but I encounter difficulties connecting to the database while running the ...

Retrieve the values of two inputs from outside of the event

How can I access the values of two input fields in order to perform calculations as soon as their values are updated? <script> // Accessing the values of the two input fields for immediate calculation based on user input const heightInputEl = docum ...

There was a TypeError that occurred because the object did not have the 'ajax' method available

When attempting to initialize the quoteResults Javascript function on my Wordpress site, I encounter the following error in my console: Uncaught TypeError: Object #<Object> has no method 'ajax' I have successfully utilized the code below ...

Place an element in relation to its initial position, ensuring that the x-coordinate is not set to 0

Is there a method to place an element in relation to its initial position, only excluding x=0 - meaning that the element is placed at its original vertical coordinate but sticks to the window's left edge? ...

Issue with disabled button in Angular 2 when using Chrome's autocomplete feature

In a basic login form, the login button is initially disabled with the following code: [disabled]="!password || !loginName" When Chrome's autocomplete feature fills in the values for loginName and password, the button remains disabled after the pa ...

How can a JavaScript map be created with string keys and values consisting of arrays containing pairs of longs?

Struggling with JavaScript data structures, I am trying to create a map in which the key is a string and the value is an array of two longs. For instance: var y = myMap["AnotherString"]; var firstNum = y[0][0]; var secondNum = y[0][1]; // perform opera ...