Trouble with JavaScript loading in HTML webpage

<!DOCTYPE html>
<html>
  <head>
    <title>Breakout Game</title>
    <link rel="stylesheet" href="css/style.css">
  </head>
  <body>

    <canvas width="900" height="450" class="canvas"></canvas>

    <script src="scripts/base.js"></script>
  </body>
</html>

This HTML file serves as the index file

*{
  margin: 0;
  padding: 0;
}

.canvas{
  background-color: #b7b7b7;
}

This CSS file is responsible for styling the breakout game

var canvas = document.getElementsByClassName('canvas');
var context = canvas.getContext('2d');

context.beginPath();

context.drawRect(20,30,50,40);
context.fillStyle("#0022ff");
context.fill();

context.endPath();

This is the JavaScript file where the breakout game logic is implemented. It seems there might be an issue in this code, but the user is unable to identify it despite multiple checks.

Answer №1

One reason for this issue is that within your code snippet involving the var canvas, you are utilizing document.getElementByClassName which actually returns an "array-like" object. To resolve this, I recommend using IDs instead of selecting elements by class.

Answer №2

  • Ensure to access the canvas element correctly by using <code>var context = canvas[0].getContext('2d');
    instead of
    var context = canvas.getContext('2d');
    . This is necessary when using document.getElementsByClassName since it returns a collection of elements with the specified class name.
  • Correct the method to draw a rectangle to context.rect instead of context.drawRect.
  • The correct way to set the fill color is context.fillStyle = "#0022ff"; as context.fillStyle is an attribute and not a function.
  • Replace context.endPath(); with context.closePath(); for closing the path.
  • It is unnecessary to use both context.beginPath(); and context.closePath(); in your case since context.rect already creates the path.

var canvas = document.getElementsByClassName('canvas');
var context = canvas[0].getContext('2d');


context.rect(20, 30, 50, 40);
context.fillStyle = "#0022ff";
context.fill();
* {
  margin: 0;
  padding: 0;
}

.canvas {
  background-color: #b7b7b7;
}
<canvas width="900" height="450" class="canvas"></canvas>

Answer №3

Why not try using fillRect in place of drawRect:

let canvas = document.getElementById("canvas1");
let context = canvas.getContext("2d");

context.beginPath();
context.fillRect(20,30,50,40);
context.closePath();

</script>

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

"Bootstrap Carousel veers off from center alignment and aligns to the left instead

I found some code on a different website to put together a Bootstrap 5 carousel. Unfortunately, the alignment of my carousel is off as it is positioned to the left and I would prefer for it to be centered within the container. <div class="container ...

A tiny blue spot popping up beside the roster of users

I'm working on a render function that displays a list of users with avatars and names. The issue I'm facing is that when the page initially loads, there's a blue dot to the left of each user. However, if I navigate to another page and then g ...

Fade out and slide close a div using jQuery

I am creating a new website and incorporating jQuery for animation and simplified JavaScript implementation. My goal is to have a button that, when clicked, will close a div with a fading out and slide up effect. Can this be achieved? Thank you. ...

Loop through the input template using ng-repeat with various data types

I have been working on developing a user interface for adding and modifying information in a database. To manage the database, I am utilizing breeze, displaying data using angular grid, and incorporating a ui-bootstrap modal dialog for user interaction. ...

Bootstrap3 Remote Modal experiencing conflict due to Javascript

Utilizing a bootstrap modal to showcase various tasks with different content but the same format is my current goal. However, I am encountering an issue when attempting to make the textareas editable using JavaScript. The conflict arises when I open and cl ...

How to use jQuery to extract a JSON snippet from a lengthy string

I received an AJAX response in the form of a lengthy string, which includes HTML and JSON data. The JSON object is embedded within the string and not always at the end. My goal is to extract the JSON object from the string so that I can utilize it with th ...

What is the best way to increase the spacing between buttons in a Bootstrap navigation bar?

Can anyone guide me on how to add space between each button in this Navigation Bar? I want them to be separated, similar to this example. I am using bootstrap 5. <nav class="navbar navbar-expand-lg navbar-light bg-light shadow-sm bg-body"&g ...

Programmatically setting properties for elements

I have a question about how to programmatically add a prop to a component in my React project. Here is the scenario: In the render() method, I have the following code snippet: <TextField name="password" va ...

Combining and removing identical values in JavaScript

I need to sum the price values for duplicated elements in an array. Here is the current array: var products = [["product_1", 6, "hamburger"],["product_2", 10, "cola"],["product_2", 7, "cola"], ["product1", 4, "hamburger"]] This is what I am aiming for: ...

Creating a dynamic JSON array with a single key as an array

After converting data from an excel sheet into a json array, here is the structure: [{ 'booktitle': 'Leading', 'bookid': '56353', 'bookauthor': 'Sir Alex Ferguson' }, { 'booktitle&ap ...

Sharing data between AngularJS and D3 with JSON - a guide

When working on my application controller, I typically send a request to my API. This is what it usually looks like: .state('state1', { url: '/datas/:id', templateUrl: 'myurl.com', title: 'title', ...

When quickly typing, the input formatting using a computed property in Vue.js is not getting applied

Is there a way to format data in the following manner: m:ss, while restricting the input textbox to display only 3 characters or fewer? (m = minute, s = seconds) The code snippet below successfully formats the data in m:ss format. However, when entering m ...

Error: JSON parsing failed due to an unexpected token 'S' at position 17

Trying to troubleshoot a syntax error in JSON.parse() within a product warranty registration process. Transitioning from Java to AngularJS for this project, I have an API built in PHP handling the back-end operations and a controller managing communication ...

The NPM version needs to be updated as it is outdated

Struggling with a dilemma here. My Laravel project is quite dated, and I'm unable to execute npm run dev. Let's take a look at some code: php artisan laravel --version: Laravel Framework 5.8.38 node --version: v16.16.0 This is the current Node v ...

Error: Unable to retrieve current location using 'Geolocation' in React

import "./App.css"; import { useState, useEffect } from "react"; function App() { const [lat, setLat] = useState(null); const [long, setLong] = useState(null); const [data, setData] = useState(null); const [error, setError] = u ...

Querying an array using the Contentful API

Recently, I've been experimenting with the Contentful API (content delivery npm module) and have encountered a challenge that I'm not sure how to overcome. In my Contentful setup, I have a content type called tag which consists of one field, als ...

My divs seem to overlap in strange, unpredictable ways depending on the zoom level - it's an odd phenomenon that occurs

This situation is causing me frustration... depending on the zoom level of the browser, my boxes do not align properly and it ends up looking messy (in all browsers). Any advice? Could I handle this more effectively with jQuery? HTML </div> <div ...

Ways to retrieve a JSON element and incorporate it into a CSS styling

Can someone assist me in converting a JSON object for use in CSS? I've attempted to do this using Vue.js, creating a map legend with v-for to generate the legend. However, if there is an alternative method that allows me to take a JSON object and ins ...

What is the reason behind the change in style hierarchy when using ':last-child'?

I found myself in a confusing situation where using :last-child is affecting how parent classes are being applied. The task at hand is to style the last element in a list of elements. However, upon using :last-child, the priority of styles shifts and one ...

What is the process for deselecting a checkbox?

I am facing a situation where I need to uncheck a checkbox that is always checked based on user input from another section of my form. Specifically, I have implemented an onChange="functionName" event on a select box. Can someone guide me on how to accom ...