An uncomplicated application designed to showcase a moving sphere

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var canvas_element;
var initial_x = 200;
var initial_y = 300;
var x_movement = 1;
function start_canvas()
{setInterval(draw_circle, 10);
 canvas_element = bouncing_ball_canvas.getContext('2d');
  }
  function draw_circle()
   {
   canvas_element.clearRect(0,0, 1000, 500);
   canvas_element.beginPath();
   canvas_element.fillStyle="#FF0000";
   canvas_element.arc(initial_x, initial_y, 50, 0+initial_x/50, Math.PI*2+initial_x/50, true);
   canvas_element.lineTo(initial_x, initial_y);
   canvas_element.stroke();
   if( initial_x<0 || initial_x>1000) x_movement = -x_movement;
   initial_x += x_movement;
   }
  </script>
  </head>
  <body>
  <canvas id="bouncing_ball_canvas" width="1000" height="500">
  </canvas>
  <body onLoad="start_canvas();">
  </body>
  </html>

Here we have a program that creates a moving ball using HTML and JavaScript. The ball moves in a jerky motion due to its blinking effect. Do you know how we can fix this issue?

Answer №1

Don't forget to declare the variable bouncing_ball_canvas

Make sure to add this line:

bouncing_ball_canvas = document.getElementById("bouncing_ball_canvas");

prior to declaring canvas_variable.

UPDATE:

The issue is in this particular line of code:

canvas_variable.arc(init_x, init_y, 50, 0+init_x/50, Math.PI*2+init_x/50, true);

Simply change the last parameter to false and it should resolve the problem.

Answer №2

The blinking is a result of an incorrect calculation. To correct this, you must first calculate the perimeter using the formula: 2*pi*r. Then proceed with a basic cross product:

distance = x
perimeter = 2*pi

This will give you the angle in radians: distance*2*pi/perimeter

To implement these calculations, follow these steps:

const getAngle=function(distance) {
    return distance*2*Math.PI/perimeter;
}
const getPos=function(x, y, angle, r) {
    return [x + Math.cos(angle)*r, y + Math.sin(angle)*r];
}
canvas_variable.arc(init_x, init_y, 50, 0, Math.PI*2, true);
canvas_variable.moveTo(..getPos(init_x, init_y, getAngle(init_x-starting_x), r));
canvas_variable.lineTo(init_x, init_y);
canvas_variable.stroke();

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

The navigation bar alignment to the right is malfunctioning

I'm puzzled as to why the navbar-right class is not properly closing out the two navigation bar elements on the right. Despite adding the correct code, it doesn't seem to be working as expected. <nav class="navbar fixed-top navbar-toggleable- ...

React - Render an element to display two neighboring <tr> tags

I'm in the process of creating a table where each row is immediately followed by an "expander" row that is initially hidden. The goal is to have clicking on any row toggle the visibility of the next row. To me, it makes sense to consider these row pa ...

What is the best way to eliminate an animation from a component while using it within a different Angular Component?

I have developed an Angular Component that enhances the look of a photo with styling and animation effects. Now, I want to utilize the same styling for another component without applying the animation. Styling and Animation for the photo: .pic { position ...

Inject Angularjs Controller into Module Once DOM is Initialized: Tips and Tricks

When injecting new DOM elements with a controller, I encountered the following issue: app.controller('cart', function ($scope, $http) { $scope.content = { label: "hello, world!", }; }); var $html = '<div ng-controller="c ...

How to handle javascript and json file processing?

My json data structure is as follows: var json = { "A": { "A1": { "A11": "A", "A12": "B", "A13": "C" }, "A2": { "A21": ...

What is the most efficient way to send multiple arrays by selecting checkboxes?

Currently, I am faced with a challenge where I have a selection of items from a list that need to be submitted in the form of three different arrays with distinct values to PHP. These arrays include: Device id, Client comment, and Manufacturer comment. < ...

Using a variable name to retrieve the output in JavaScript

I created a unique JavaScript function. Here is the scenario: Please note that the code provided below is specific to my situation and is currently not functioning correctly. analyzeData('bill', 'userAge'); Function analyzeData(u, vari ...

Executing conditions in a JavaScript browser

Currently, I am utilizing a JS library known as fallback.js. This library loads all its <link> elements at the bottom of the <head> tag. However, I am facing an issue where I need to load certain stylesheets at the very end, but they require IE ...

Responsive design and column alignment dilemma

I'm attempting to create a layout using Bootstrap 3.2.0 with tiled divs in a single row for screens wider than 768px. The divs have heights of either 50px or 100px, controlled by the classes "home-height-single" and "home-height-double," and widths ad ...

Angular 2 - The constructor of a class cannot be called without using 'new' keyword

Currently, I am working on integrating the angular2-odata library into my project. This is the code snippet I have: @Injectable() class MyODataConfig extends ODataConfiguration { baseUrl = "http://localhost:54872/odata/"; } bootst ...

Displaying or concealing fields through Javascript depending on the category type of the results item

I am facing an issue with displaying certain fields in each individual property search result based on the property type. For example, if a property is classified as Land, I do not want the bedrooms and bathrooms fields to be visible, but if it is a Villa, ...

Moving the final item in the list to the end

I've chosen to implement the Vali Admin theme and am currently attempting to move the last list item in the left sidebar to the bottom. While I have limited experience with flexbox, I decided to change the menu to display: flex and followed the steps ...

Try implementing a body template when using the mailto function

Is there a way to customize an HTML template for the mailto() function body? For example, suppose I have the following link: echo "<a href="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="97f2faf6fefbd7f0faf6fefbb ...

Attempting to configure Kafka consumer and producer components

Trying to establish a basic producer-consumer flow with Kafka, utilizing node-rdkafka Operating in debug: 'all' mode, the logs display: Producer: test [0]: MessageSet with 1 message(s) delivered Consumer: Fetch topic test [0] at offset 38 (v2) ...

I am curious about the significance of the "=>" symbol within the Ionic framework

I utilized the documentation provided on the Ionic website to incorporate Firebase into my mobile application. this.firebase.getToken() .then(token => console.log(`The token is ${token}`)) // store the token server-side and utilize it for sending not ...

Invalid component exception: The element type is not valid in React Native

In my React Native App.js file, I have included the following code snippet import { StatusBar } from 'expo-status-bar'; import React, { useRef } from 'react'; import { StyleSheet, Text, View, Canvas } from 'react-native'; impo ...

What is the best way to make one element match the height of another element?

I am facing an issue with the height of my two columns as I have another column separating them. The challenge is to make the left and right columns extend in height based on the content added to the center column. One important point to consider is that ...

Issue with marker functionality on Google Maps JavaScript API when conditions are not functioning correctly

I am currently working on plotting different markers on Google Maps by extracting data from a CSV file. I have incorporated the parsecsv-0.4.3-beta library to read the CSV file, and everything is functioning smoothly except for when I compare two fields to ...

React component failing to render even when event is triggered

For my latest project, I am creating a blog using react, next.js, and json-server. The blog is coming along nicely with dynamically loaded blog posts and UI elements. However, I've hit a roadblock when it comes to loading comments dynamically. The sp ...

Playing only audio and no video in an Android WebView using HTML5

I am currently facing a challenge with a webpage that includes an html5 video and css3 animations. While the web page functions perfectly on an android device's browser, I am experiencing laggy, glitchy, and jumpy animations when using hardware accele ...