Creating a Dynamic Ball Animation in JavaScript using Canvas

What should I tweak in the code to make the ball bounce upward at the beginning?

I am completely lost here and have experimented with numerous ideas without success. I feel like I must be overlooking something simple.

It seems like the key part of the code that needs to be adjusted is related to the if statement for x, but I'm stuck at this point.

function update() {
    x += 1;
    y += yspeed;
    yspeed += gravity;
    if ( y >= context.canvas.height)
    {
        yspeed *= -1;
    }
    if ( x <= 0 || x >= context.canvas.width)
    {
        x = (x + context.canvas.width) % context.canvas.width;
    }
  }

Currently, the ball initiates its bounce in a downward direction. How can I modify it to start by bouncing upwards?

Answer №1

yspeed plays a key role in determining the vertical speed of your ball, and it needs to be specified in the code. Experiment with changing it to a negative value like -10 to see how it affects the ball's movement. What ultimately brings the ball back down to the ground is the force of gravity.

Check out this interactive example by clicking 'Run code snippet' below:

var gravity = 1;
var yspeed = -10;
var x = 10;
var y = 50;
document.getElementById("ball").style.left = x + "px";
document.getElementById("ball").style.top = y + "px";

function loop() {
  document.getElementById("ball").style.left = x + "px";
  document.getElementById("ball").style.top = y + "px";
  x += 1;
  y += yspeed;
  yspeed += gravity;
}
var interval = setInterval(loop, 60);
<svg height="20" width="20" id="ball" style="position:relative">
  <circle cx="10" cy="10" r="10" fill="red" />
</svg>

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

Transferring information about service events to a controller in Angular

I am facing an issue with some audio elements in my service that listen for the "ended" event. I am looking for a way to pass this message to an angular controller. Currently, my service code looks like this: Audio.addEventListener "ended", (-> ...

What is the best way to store article IDs using Javascript or HTML?

On my web page, I have a collection of links that users can interact with by clicking and leaving comments. These links are loaded through JSON, each with its unique identifier. But here's my dilemma - how can I determine which link has been clicked? ...

Creating trails by following the cursor's movement in KineticJS

Currently, I am working on a drawing application using KineticJS. While I have successfully used it to draw shapes and straight lines by following the method outlined in KineticJS - Drawing Lines with Mouse, I now need to draw a line along the mouse's ...

Numerous attributes for displaying ngOption values

I have an item that resembles the following: $scope.team = [ { name: "John", number: 1 }, { name: "Emma", number: 2 } ]; Currently, in my HTML code, I am using ngOption to populate a dropdown menu with values from the object. < ...

Verifying if any of the entries in a specific index contain a null value

Here is the structure I am working with: { "subs": [ { "status": "1", "run_settings": null, "ward": "/asda/asd/ada" "value": null, "name": null }, { "status": "0", "run_settings": null, "ward": ...

The first three AJAX requests are successful, but the fourth one fails to reach the PHP script

I am currently working on cascaded selects (a total of 4) that retrieve data from a database. To populate them, I use SQL queries based on the selection made in the previous select element. To establish communication between the select element and the subs ...

Please add color to the space beneath the line in a highchart

I have been tasked with customizing a line chart that was not originally created by me. The application pulls data from a database and organizes each element by hour before displaying it on the chart. When you hover over a point, the interface looks like t ...

Issues with Angular application navigation in live environment

While my website functions perfectly on the development server, I encounter a strange error when I publish it to production on GitHub pages. Visiting the URL (yanshuf0.github.io/portfolio) displays the page without any issues. However, if I try to access y ...

Using Angular JS to submit forms on a regular basis

My HTML form is set up within an Angular controller with inputs, action, and other elements already defined. The only issue I'm facing is that the form does not have a traditional submit button. Instead, there is a separate button on the page outside ...

Material UI is failing to apply its styles

I tried customizing the default theme provided by Material UI, but unfortunately, the styles are not applying. Can anyone help me with this issue? In My Header.js file, I faced an issue where the customized style was not being applied as expected. const u ...

Automatically adjusting maps according to internal criteria

I have an example of a map that looks like this const Map = new Map().set('123', [ [ 'foo', 'bar' ] ]).set('456', [ [ 'baz', 'qux' ], [ 'quux', 'corge' ] ]); /* The structure ...

The script for tracking cursor coordinates is incompatible with other JavaScript code

<html> <script language="javascript"> document.onmousemove=function(evt) { evt = (evt || event); document.getElementById('x').value = evt.clientX; document.getElementById('y').value = evt.clientY; document.ge ...

Error encountered: EPERM - Unable to perform operation on Windows system

Recently, I executed the following command: npm config set prefix /usr/local After executing this command, I encountered an issue when attempting to run any npm commands on Windows OS. The error message displayed was as follows: Error: EPERM: operation ...

open a new window with a reference based on the name

In order to obtain a reference to the currently open window, I utilize the following code: var refWindow = window.open("mypage1", "name_mypage"); If I wish to close the window, I simply use this command: refWindow.close(); When I refresh the screen (by ...

Error [ERR_MODULE_NOT_FOUND]: Module could not be located in vscode

Issue with VS Code: Module Not Found Error View the image associated with the erroreN.png ...

dynamically open ngx-bootstrap accordion panels

I implemented the ngx-bootstrap accordion feature to display a list of blog posts. Below is the template structure: <accordion id="blog-list"> <accordion-group *ngFor="let post of posts; let first = first;" [isOpen]="first" id="post-{{post.i ...

most efficient method to execute numerous API requests at the same time

Currently, I am developing a backend using expressJS. Imagine that I need to make 10,000 calls to an API consecutively and store the obtained data in a database. What would be the most effective approach for achieving this task? Is it possible that Promis ...

The route is displaying the variable as 'undefined' when I attempt to access it

I had set up CRUD for two different models (venues & artists) - venues works fine, but when I try to access 'artists/index', it gives me an error saying 'Artists is not defined'. After examining the code, I believe I need to do two ...

Storing API data in localStorage using VueJS: A step-by-step guide

As I work on practicing building a simple SPA with VueJS, one of my current tasks involves listening to an API and storing certain data in the browser's localStorage. However, my experience with VueJS is still limited, so I'm unsure about how to ...

Solution to trigger CSS :hover to refresh following a transition (such as expanding a menu)

While there are existing discussions on this topic, I am presenting my query for two specific reasons: It introduces a potential alternative solution The demo code could be helpful to individuals looking to emulate a menu Following a CSS transition, the ...