Tips on smoothly transitioning an object along a path in an HTML5 Canvas and ensuring that the previous object's residue does not linger behind

Is there a way to smoothly move an object over a line in HTML5 without leaving old objects behind? I need help achieving a seamless movement of a ball across a line.

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

context.beginPath();
context.moveTo(10, 10);
context.lineTo(400, 10);
context.stroke();


function clickToAddBall() {
    // Do something
}

function gameLoop() {
    var loop = 400;
    setInterval(function() {
        loop = loop - 10;
        drawABall(loop);
    }, 200);
}
gameLoop();

function drawABall(positionX) {

    context.beginPath();
    context.arc(positionX, 10, 5, 0, 2 * Math.PI, false);
    context.fillStyle = 'green';
    context.fill();
    context.lineWidth = 5;
    context.strokeStyle = '#003300';
    context.stroke();

}

http://jsfiddle.net/noppanit/z5VwL/2/

Answer №1

Make sure to refresh the canvas before each redraw. I included

context.clearRect(0,0,578, 200 );

in the draw function...

function drawABall(positionX) {
      var centerX = canvas.width / 2;
      var centerY = canvas.height / 2;
      var radius = 5;

      context.clearRect(0,0,578, 200 );   

      context.beginPath();
      context.arc(positionX, 10, radius, 0, 2 * Math.PI, false);
      context.fillStyle = 'green';
      context.fill();
      context.lineWidth = 5;
      context.strokeStyle = '#003300';
      context.stroke();

}

As a demonstration, here's an example on jsfiddle.

http://jsfiddle.net/z5VwL/3/

Answer №2

If you're looking for a simple solution, consider redrawing the screen or clearing it just before drawing. Add this function to your game loop:

function clearScreen() {
     context.clearRect(0, 0, canvas.width, canvas.height);
 }

Your updated game loop might look something like this:

function gameLoop() {
    var loop = 400;
    setInterval(function() {
        loop = loop - 10;
        clearScreen();
        drawABall(loop);
    }, 200);
}
gameLoop();

To prevent lines from disappearing, create a lineDraw function and include it in the loop like so:

function gameLoop() {
    var loop = 400;
    setInterval(function() {
        loop = loop - 10;
        clearScreen();
        drawLine();
        drawABall(loop);
    }, 200);
}
gameLoop();

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

Ways to troubleshoot the error message 't.rangeslider is not a function' in which rangeslider is a personalized function

I'm experiencing an issue with a function assigned to a variable that is throwing an error. Here is the code snippet: $(".sliderRange").each(function() { var t = $(this); t.rangeslider({ polyfill: !1, onSlide: function(e, a) { var n = ...

A new module is unable to load Angular Material

Recently, I developed an Angular material module similar to a core module. import { NgModule} from '@angular import {MatCheckboxModule} from '@angular/material/checkbox'; @NgModule({ imports: [ MatCheckboxModule ], exports: [ ...

Selenium - Implementing browser shutdown cleanup steps in Selenium tests

I have encountered a challenge where I need to execute some tasks before the close button on Google Chrome browser is clicked and the window is closed. This involves logging out of the website among other things. Completely clearing cookies is not an opti ...

Adjust the size of the webpage to ensure compatibility with various screen sizes for

I designed the website using bootstrap, but I'm facing an issue when resizing the site in the browser - the text is not adjusting properly. I have tried various solutions within Bootstrap, but nothing seems to be working effectively at the text level. ...

Preserve router animations using :key attribute, while ensuring that parent views do not reload

My app utilizes :key="$route.path" in the router view for transitions, but this approach leads to the child route base view being refreshed and triggering certain APIs again. Routes: { path: "/some-route", component: () => impor ...

Choose only the options that are present in both arrays

I am working on creating a multiple select feature that displays all nodes, but only checks the ones that are present in 2 arrays. My front end is developed using Angular 8 and TypeScript. private mountSelect(nodesInRelation, lineApiKey) { console.lo ...

Error in Bootstrap modal: The function 'scrollTop' is not defined

I'm puzzled by the error message I keep getting: 'Cannot call method 'scrollTop' of undefined' It occurs when I click on the link that triggers the modal to appear. I am using jQuery 1.11 and bootstrap 3.1.1 for this. Here is t ...

Tips on eliminating extra whitespace in cards

I have created a card with an image and some content, but there seems to be unwanted space between the two elements. How can I remove this space so it looks consistent across all devices? Here is the HTML code: <div class="project-card hidden" ...

Plugin for jQuery that paginates text when it overflows

Looking for a solution here. I have a fixed width and height div that needs to contain text. If the text exceeds the size of the div, I want it to paginate with dots at the bottom of the page indicating each page, similar to slideshow functionality. Are t ...

Is there a way to detect and halt file writing in node fs if an error occurs?

While working on writing a file, I made an error by using the wrong variable. This mistake led to the file being written incorrectly, resulting in everything it contained being deleted and left blank. fs.writeFile( path.join(__dirname,"../example/pa ...

What sets Joomla file inclusion apart from the rest?

Can someone please explain the difference between including a JavaScript script file in the following two ways? I created this within a system plugin in Joomla and included the JavaScript file inside the "onAfterInitialise" function. 1) <script type ...

Syntax error occurs while attempting to render the return statement in a React Component

Just starting out with React and encountering a syntax issue that has me stumped. I'm working on a React Component and I thought I had the opening/closing { & }'s correct, but clearly there's something missing based on the error message it&a ...

How can I eliminate the padding from an image button in Bootstrap 5?

I am facing an issue with removing padding from a button that has an image inside it. I have tried using style="padding: 0px !important" and the p-0 class, but it doesn't seem to work. Switching the <button> to <a> removes the padding, but ...

What's the reason for fadeIn() not functioning properly?

Here's the HTML code I'm working with: <!DOCTYPE html> <html> <head> <title>Furry Friends Campaign</title> <link rel="stylesheet" type="text/css" href="styles/my_style.css"> </head ...

Creating dynamic images in JavaScript by assigning URL paths from string variables

Currently, I am utilizing JavaScript to parse through an XML file. One interesting aspect of the XML is that it contains URLs which link to images like this one: http://localhost/pic.jpg Throughout the parsing process, I am storing each URL as a string va ...

Using .addEventListener() within a function does not successfully generate the intended event listener

For a while, my program ran smoothly with the line canvas.addEventListener("click", funcName, false);. However, I recently realized that at times I needed to replace this event listener with another one: canvas.addEventListener("click" ...

Designing tables and adherence to WCAG 2 accessibility standards

I'm aware that WCAG 2.0 allows tables for layout purposes, but I keep encountering an error in achecker despite this: Error 245: Data table with multiple rows/columns of headers does not utilize id and headers attributes to identify cells Resolution ...

Having trouble retrieving the current pathname value within the event listener

I have implemented a scroll event listener that triggers a URL change when a specific section is reached. React.useEffect(() => { window.addEventListener('scroll', handleScroll); return () => { window.removeEventListener('scro ...

Parsing a Jackson object in JavaScript that includes JsonIdentityInfo

Hey there (excuse my English) I've been working on an AngularJS front-end website that consumes a web service which produces JSON with Spring MVC. The Spring MVC uses the JsonIdentityInfo option for serialization, so each object is only written once ...

The creation of a MozillaBrowserBot object has encountered an error

Attempting to access the MozillaBrowserBot object in Mozilla JS has been unsuccessful for me. The code I utilized is shown below: function externalApplication(){ var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Com ...