Creating an interactive animation of bouncing balls within an HTML5 canvas using JavaScript

function refBalls(){
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var circles = [{x:40,y:100,r:20,color:'black',vx:5,vy:10}]
function draw(){
    ctx.beginPath();
    ctx.arc(circles[0].x, circles[0].y, circles[0].r, 0, 2 * Math.PI);
    ctx.fillStyle = "blue";
    ctx.fill();
    if( (circles[0].x + circles[0].r + circles[0].vx > c.width + c.style.left) || (circles[0].x - circles[0].r + circles[0].vx < c.style.left) ){
        circles[0].vx = -circles[0].vx;
    }
    circles[0].x += circles[0].vx;
    requestAnimationFrame(draw);
}
requestAnimationFrame(draw);}

I am noticing an issue where the ball is not moving smoothly on the canvas. It seems to be leaving a trail behind it instead of appearing as a solid continuous movement. Any suggestions or solutions would be greatly appreciated! Here is a screenshot of what I'm currently seeing in my browser

Answer №1

It's important to start fresh by clearing the canvas before drawing each frame, similar to how video games display their graphics on screen.

Check out these resources for more information: How to clear the canvas for redrawing

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

Using XSLT with JavaScript

I am currently working with a set of XML files that are linked to XSLT files for rendering as HTML on a web browser. Some of these XML files contain links that would typically trigger an AJAX call to fetch HTML and insert it into a specific DIV element on ...

Can you help me pinpoint the tags related to mail?

The email address appears in various locations throughout the page. For instance <div> <p><a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a3c2e3c28dd1d6">[email protected]</a></p> </div> ...

Display a div based on user selection using Ajax and Laravel

There are two div elements on the index page containing a datatable. By default, these two divs should be hidden. When an option is selected from the dropdown menu, the corresponding div should be displayed. The webpage is designed for searching within a ...

The JavaScript function prints the variable using `console.log(var)`, however, it does not assign `var2` to

I've been following a tutorial on implementing push notifications in VueJS from this link. After running the register function on the created hook, I encountered an issue: register() { if ("serviceWorker" in navigator && "PushManager" in window ...

Simplest method for defining an associative array

Looking to create an array in the format shown below: [0: 0, 1: 1, 2: 2] This is achieved using the following code snippet: var arr = []; for(i=0; i<3; i++){ arr[i] = i; } Upon execution, my array appears as follows: [0, 1, 2] The values with ...

React JS: The active text object in Fabric JS canvas becomes uneditable after attaching an event listener

After implementing event listeners for copy-paste, cut-paste, and movement functionalities in different directions, I encountered an issue when trying to edit the active text object on the canvas. I am utilizing the fabricjs-react module. Below is the cod ...

Is it possible to utilize a designated alias for an imported module when utilizing dot notation for exported names?

In a React application, I encountered an issue with imports and exports. I have a file where I import modules like this: import * as cArrayList from './ClassArrayList' import * as mCalc1 from './moduleCalc1' And then export them like t ...

Smart method for repositioning multiple elements on the display

Imagine we have multiple divs displayed on a screen: https://i.stack.imgur.com/jCtOj.png ...and our goal is to move them collectively, either to the left: https://i.stack.imgur.com/KBfXC.png ...or to the right: https://i.stack.imgur.com/c1cUw.png An ...

What is the process for generating a dynamic array in typescript?

Looking to create a TypeScript dynamic array with the desired format: const display = [ { id: 1, displayName: "Abc1" }, { id: 2, displayName: "Abc2" }, { id: 3, displayName: "Abc3" } ] Attempted the following code ...

Turning a text into a JSON data structure

How can I make JavaScript recognize a string as JSON? I have a function that only works when passed a JSON object. If I pass a string with the same format as JSON, it doesn't work. I want to find a way for the function to treat the string as JSON, ev ...

The Three.js environment experiences lag and a decrease in performance

In the threejs scene, there is a sphere geometry and a plane geometry. The sphere is textured with an image, while the plane geometry is textured with 2D text. The plane geometry is also attached with a click event. When clicking on the plane geometry, ...

When attempting to display or hide elements within a function, the foreach loop only chooses the last variable when referencing the `div`

As I navigate through a straightforward foreach loop to retrieve "blog posts", the page displays basic information about each post along with a 'reply' and 'delete' button. Clicking on the 'reply' button reveals a small form b ...

What is the best way to display text from a file on a different html page using jQuery's json2html?

Here is the json data: var data = [ { "name": "wiredep", "version": "4.0.0", "link": "https://github.com/taptapship/wiredep", "lice ...

Enhancing the ShaderMaterial attribute in three.js

Exploring the three.js tutorial on shaders, we discover a technique for updating uniform values of a ShaderMaterial: var attributes = { displacement: { type: 'f', // a float value: [] // an empty array } }; var uniforms = { amplitu ...

Feasible: Embedding my complete website using custom HTML code into an iframe

I have the HTML for a website saved in a JavaScript string and I want to display it within an iframe. How can I insert this HTML string into the iframe and make the website appear? I have attempted to use this.src = HTML_STR; this.innerHTML = HTML_STR; but ...

Is there a way to automatically update a webpage?

When two computers, pc1 and pc2, are on the same page and pc1 changes the status of a field, is there a way to update pc2's aspx page without needing to refresh it? ...

Having trouble retrieving an object through a GET request in Node.js with Express

Currently, I am going through a tutorial on Node.js by Traversy Media and I have encountered an issue that has me stumped. The problem arises when I attempt to retrieve the response of a single object from an array of objects using the following code: app ...

Issue with ng-repeat directive not functioning

Let's dive into this directive: .directive('img', function () { return { restrict: 'E', link: function (scope, elem, attr) { if (attr.src && attr.type === "extension"){ var ...

Combine two flex directions within a single container

Is it possible to achieve the following layout within a single container? I understand that using display: flex; justify-content: center, align-items:center can center all elements, but can I specify two of the divs to be displayed in a column rather than ...

Getting the iframe onload event in an ASP.NET application

I have integrated ReportViewer to display SSRS reports on my .aspx page. However, since the ReportViewer is rendered as an iframe in the browser, I am looking for a way to trigger a JavaScript function every time the iframe loads. Using window.onload w ...