Attempting to generate a dynamic animation of a bouncing sphere confined within a boundary using components, but encountering

I'm new to JavaScript and currently working on a project involving a bouncing ball inside a canvas. I was able to achieve this before, but now I'm attempting to recreate it using objects. However, despite not encountering any errors, the animation is not working as expected and I'm struggling to identify the problem. Any guidance would be greatly appreciated. The canvas displays properly, but the ball does not appear.

<canvas id="sCanvas" width="550" height="550" style="border: solid"></canvas>
<body>

<script type="text/javascript">

    //variables
    var c = document.getElementById("sCanvas");
    var ctx = sCanvas.getContext("2d");
    var cHeight = sCanvas.height;
    var cWidth = sCanvas.width;


    //object


    //create the sphere object
    class Sphere {
        constructor(aRadius){
            //add properties to object
            this.radius = (aRadius || 15);
            this.colour = "green";
                 
            this.xPos = 30;
            this.yPos = 30;
            this.speedX = 2;
            this.speedY = 5;

        }

        drawMe(){
            ctx.beginPath();
            ctx.arc(this.xPos, this.Ypos, this.radius, 0, Math.PI *2, true);
            ctx.fillStyle = this.colour;
            ctx.fill();
        }

        moveMe(){
            this.yPos += this.speedY;
            this.xPos += this.speedX;

            if (this.yPos > 540){
                this.speedY =- this.speedY
            }

            else if (this.yPos < 10){
                this.speedY =- this.speedY
            }

            if (this.xPos > 540){
                this.speedX =- this.speedX
            }

            else if (this.xPos < 10){
                this.speedX =- this.speedX
            }
        }
    }


    var ball = new Sphere();

    function render(){
        requestAnimationFrame(render);
        ctx.clearRect(0, 0, cWidth, cHeight);
        ball.drawMe();
        ball.moveMe();


    }

     render(); 

</script> 
</body>

Answer №1

When writing your drawMe() function, be careful not to use this.Ypos instead of this.yPos for ctx.arc().

A suggestion for improvement is to consider the size of the ball in your moveMe() method rather than hard-coding numbers. This is important because you have already made the ball radius a variable size in your constructor.

If you were to change the ball radius to 35, part of it may exceed the dimensions of the box when hitting the wall.

~Pat

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

There has been an issue with parsing the JSON file due to an invalid character found at

I keep encountering a parse error whenever I attempt to send a post request to the server. $.post("../php/user_handler.php", formData, function(data) { var result = JSON.parse(data); if(result.status === 'error') { ...

tips on launching a pre-existing react native project

Trying to run a project downloaded from someone else can be quite challenging. I encountered some issues where the project just wouldn't start, and now I'm completely stuck. Can anyone help me out? https://github.com/sunlight3d/react_native_v0.4 ...

Attempting to deploy my initial Google Cloud Function, encountering an error message indicating that Express is not detected

Currently in the process of deploying my first Google Cloud function, the code for which can be found here: https://github.com/rldaulton/GCF-Stripe/blob/master/Charge%20Customer/index.js The code starts with the following line: var app = require('e ...

Diving deep into the reasons behind a test's failure

Currently, I am using Postman to test the API that I am developing with express. In this process, I am creating a series of tests. Below is a brief example: tests["Status code is 200"] = responseCode.code === 200; // Verifying the expected board var expe ...

Error: The function loadJSON has not been declared

Currently utilizing the Atom text editor, I have successfully installed node.js along with npm install -g json. The installation process was smooth and the version information displayed correctly in the command prompt window. Running a server using nodemon ...

methods for sorting firestore data in react on client side

Fetching data from firestore and applying filters const [projects, setProjects] = useState([]); const fetchData = (sortBy = "NAME_ASC") => { const unsubscribe = firebase .firestore() .collection("projects") ...

The reactivity of Vuex and Vue does not work as expected when a dictionary is used as a

What is the best approach to make a dictionary reactive as one of my store variables? Unlike an array, dictionaries are not reactive by default. Here's a minimal example I've created: Check out this example on CodeSandbox ...

Ways to refresh the appearance of clothing in Three.js

Currently, I am diving into the world of Three.js. My latest project involves adapting a shader that I originally created in Shader Toy to be displayed on my own webpage. The shader itself is a procedural terrain where users can navigate using the WASD key ...

Managing multiple sets of data in a structured form similar to an array

How Do I Send Form Data as an Array? Take a look at the code snippet below. I'm having trouble setting the index in product_attribute['index must be here']['key'] <tr v-for="index in attributes"> <td class="text-left ...

How can you utilize jQuery's .post() method to send information as an object?

When I send a .post() request like this var data = $(this).serialize(); $('form').on('submit', function(event) { event.preventDefault(); $.post('server.php', data, function(data) { $('#data').append( ...

Automatically Populate Text Field with the URL of the Current Page

I am hoping to automatically fill a hidden text field with the URL of the current page so that I can keep track of where form submissions are coming from. This simple solution will help me streamline my inquiry responses and save time. To clarify, upon lo ...

When an element is dragged within the mcustomscrollbar container, the scroll does not automatically move downward

I am facing an issue where I have multiple draggable elements inside a Scrollbar using the mcustomscrollbar plugin. When I try to drag one of these elements to a droppable area located below the visible area of the scroller, the scroll does not automatical ...

Leverage the Frontend (Headless Commerce) to utilize the Admin API and retrieve products from Shopify

Attempting to retrieve products from Shopify using the Admin API (GraphQL) through my frontend. I utilized the following code: *I implemented "axios" on Quasar Framework, utilizing Headless Commerce const response = await this.$axios({ url: "https: ...

analyzing properties through unit testing

Currently in the process of writing unit tests for computed properties. I have a file called fileOne.ts : export const fileOne = () => { const fx1 = computed ( () => { ... } ); const fx2 = computed ( () => { ... } ); const fx3 = comp ...

Issue with thymeleaf causing malfunction in top-bar navigation on foundation framework

Looking for advice on creating a navigable menu using Foundation's "top-bar" component in an HTML template file with Spring MVC + thymeleaf. The menu bar appears but the sub-menus are not displaying when hovering over them. Sub-menus related to main ...

The presence of asynchronous JavaScript can lead to errors due to missing functions in JavaScript

I've encountered an issue with a jQuery script that I modified by adding an ASYNC attribute. Surprisingly, it functions correctly in Firefox but encounters intermittent failures in both Chrome and IE browsers. Here's the PHP code snippet respons ...

Navigate to a different web page within the body tag without changing the current URL by utilizing a hash symbol

I am working with two HTML files, index.html and about.html. My goal is to display the content of about.html within my index.html without navigating away from it. After observing many websites, I noticed that they often use #about in their URLs to dynamic ...

Click a button to adjust the height of an element

My webpage features a dashboard with tabs on the left and corresponding content on the right. To ensure proper alignment, I have utilized Bootstrap to create two columns - one for the tabs and one for the content. However, I am facing an issue where the bo ...

Iterate through the JSON response and send it back to Jquery

I'm almost done with my first jQuery autocomplete script and just need some assistance in understanding how to make the found elements clickable as links. Here is a snippet of my JavaScript code: $(document).ready(function() { var attr = $(&apos ...

I am developing a quiz application using JavaScript, and I am wondering how I can smoothly transition from one question to the

I'm working on developing a quiz application and I'm facing an issue where my quiz is skipping question 2 when moving from one question to the next using the "next" button. I have a total of 3 questions in my quiz and for some reason, it jumps fr ...