Why does the outcome of running this code vary each time?

I've been working on a code project to create 10 bouncing balls of different colors, but I'm encountering an issue where only one or two balls appear with different colors or the animation works perfectly only 1 out of 10 times. Any thoughts on why this might be happening? Canvas Animation

<body>
<canvas id = "canvas" width="600"  height = "500"> </canvas>

<script>

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var width = 300 //changes canvas size
var height = 400
width = canvas.width
height = canvas.height
    /* In this constructor, the starting position
    of the ball is set to this.x and this.y 
    */
var Ball = function () {
    this.x = Math.random() * canvas.width;
    this.y = Math.random() * canvas.height;
    this.xSpeed = -2; // -2 means 2 pixels left for every step of animation.
    this.ySpeed = 3;
    var circle = function (x, y, radius, color, fill) { //function to make drawing circles faster
            ctx.strokeStyle = color
            ctx.beginPath();
            ctx.arc(x, y, radius, 0, Math.PI * 2, false);
            if (fill === true) {
                ctx.fillStyle = color;
                ctx.fill()
            }
            ctx.stroke();
        }
        // The Ball maker
    x = Math.floor(Math.random() * 10)
    myColors = ["Green", "Red", "Orange", "Yellow", "Chocolate", "Brown", "Silver", "Black", "Purple", "Blue"]
    Ball.prototype.draw = function () {
        circle(this.x, this.y, 3, myColors[x], true)
    };
    // this will move the balls

    Ball.prototype.move = function () {
        this.x += this.xSpeed;
        this.y += this.ySpeed;
    };

    Ball.prototype.checkCollision = function () { //makes the balls bounce off walls
       if (this.x < 0 || this.x > width) {
            this.xSpeed = -this.xSpeed;
        }
        if (this.y < 0 || this.y > height) {
            this.ySpeed = -this.ySpeed;
        }
    }
}
var moBalls = [] //stores balls to be called later
for (var x = 0; x < 10; x++) {
    moBalls[x] = new Ball()
}
width = canvas.width
height = canvas.height
setInterval(function () {
    ctx.clearRect(0, 0, width, height);
    for (x = 0; x < 10; x++) { //takes the balls from moBalls and moves the ten of them
        moBalls[x].draw()
        moBalls[x].move()
        moBalls[x].checkCollision();
    }
    ctx.lineWidth = 4
    ctx.strokeRect(0, 0, width, height); //makes the walls
}, 30);

</script>

</body>
</html>

Answer №1

It appears that the issue might stem from the repeated use of the variable x without proper declaration using the var keyword (as mentioned by @pointy).

To rectify this, consider adding var x when generating the random number to select a color from the array and also in the for loop where the draw method is called.

Alternatively, opt for distinct variable names that reflect the purpose of each variable. For instance:

var randomColorIndex = Math.floor(Math.random() * 10)
var myColors = ["Green", "...", "Blue"]
Ball.prototype.draw = function () {
    circle(this.x, this.y, 3, myColors[randomColorIndex], true)
};

(I understand it may seem lengthy, but this is just an illustration; feel free to customize it to your preference).

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

Unable to set $_POST value when using $.ajax post request

I am a beginner in the world of PHP and JavaScript, and I have encountered an issue where I need to make changes to values in an XML document that has been read in. Specifically, I have an HTML Select element that was dynamically generated by PHP code. fu ...

Is it possible to remove individual items from a FlatList by clicking on them and updating the state?

I have a FlatList displaying items from an array called data. My goal is to remove each item individually by clicking on it, but currently when I click on one item, all items are deleted at once. Any suggestions on how to address this issue? Here's ...

What is the reason behind not being able to assign identical names to my SailsJS models and MySQL tables?

Recently diving into Sails JS, I found myself in unfamiliar territory with RESTful APIs. Following the guide, I created a User model to correspond with my existing users table. Adding attributes based on the table's columns was straightforward, and a ...

Sorting a 2D array in Javascript based on numerical values

I've come across a few similar posts regarding this issue, but none have provided solutions that work for my specific situation. I'm feeling lost on how to solve this problem (like Sort a 2D array by the second value) Let me explain the challeng ...

Launch both client and server simultaneously with a single command by utilizing Vue-cli and Webpack

Currently, I am setting up a Vue client with Vue-cli 3 that utilizes Webpack. (To start the client, I run "yarn dev --open") In addition, I am developing a server with an API for the client. (To run the server, I execute "node server/server.js") Is th ...

I am struggling to understand the significance of the $ symbol in this particular context

I came across the following snippet in a book I've been reading: `images/${Date.now()}.jpg` The curly brackets used here signify 'out of string', but I'm unsure about the meaning of $... P.S. Honestly, I didn't want to ask a que ...

Is there a way to adjust user privileges within a MenuItem?

One of my tasks is to set a default value based on the previous selection in the Userlevel dropdown. The value will be determined by the Username selected, and I need to dynamically update the default value label accordingly. For example, if "dev_sams" is ...

Would this be considered a practical method for showcasing an image with jQuery?

Is there a more efficient way to display an image once it has been loaded using this code? LightBoxNamespace.SetupLightBox = function(path, lightBox) { // Create a new image. var image = new Image(); // The onload function must come before ...

Guide on sending JSON messages between Node.js services within a Docker Compose environment

If I have two Node.js services running in a Docker Compose, one listening on port 4000 and the other on port 5000, how can I exchange JSON messages between them using Express? ...

When I attempt to utilize the API, the JavaScript implementation of a <script src=...> element seems to interfere

Within one of my HTML files, I encountered the following line near the top: <script src="//maps.google.com/maps/api/js?key=apikey"></script> The API key is currently hardcoded in this file, but I would like to use a configuration option store ...

Is there more to AJAX than just fetching a JSON file?

I am in need of using AJAX to achieve my goal. My aim is to have the content of specific subpages displayed in the HTML markup below when a particular link in a list is clicked. This data can be readily accessed from the database via the CMS's API (I ...

After mapping in JavaScript, delete the property name

Is there a way to exclude the property name from the returned value? I want to eliminate the property name "projects: [ ]" from the output. router.get("/", (req, res, next) => { Project.find() .exec() .then(docs => { res.status(200) ...

Waveform rendering in HTML5 using wavesurfer.js struggles to handle large mp3 files

Recently, I was considering incorporating wavesurfer.js into one of my projects so I decided to explore the demo on To test it out, I uploaded a large mp3 file (approximately 2 hours long) onto the designated area in the middle of the page. It appeared to ...

Radio buttons with multiple levels

Looking to implement a unique two-level radio button feature for a specific option only. Currently, I have written a logic that will display additional radio buttons under the 'Spring' option. However, the issue is that when it's selected, t ...

What is the best way to pass the ng-repeat value to the controller in AngularJS

On my webpage, I am trying to utilize ng-repeat with an array like the one below: var array = [{name: Bill, age: 12, number: 1}, {name: Tyrone, age: 11, number: 2}, {name: Sarah, age: 14, number: 3}]; I want to have a button that, when clicked, sends eit ...

Can anyone assist me with this HTML/jQuery code?

Despite my efforts, I've been unable to achieve success. The challenge I'm facing is with duplicating controls for adding images. I have a button and a div where the user can choose an image by clicking the button. The selected image appears in ...

Guide to establishing a connection to the Companies House API: Essential guidelines on setting up cURL headers and requisite API key specifications

I am attempting to establish a connection with the UK Companies House API, preferably using JavaScript. However, I am currently trying to set up this PHP version. How can I obtain access to the API using an API key? PHP: public function GetCompanyHouse( ...

Asynchronously retrieve the result from a previous NodeJS chain and forward it to a nested function for processing

When uploading an image from the client as Base64 to the server, I need to: Save the file to disk Get the result of the save (first chain) and pass it to the next chain Check the result in the next function using that(), if it's true, update the dat ...

Turning a lambda function into a function that is compatible with next.js API: A step-by-step guide

I am currently using an Instagram API to retrieve data from my personal profile, which is triggered by a lambda function on Netlify. Here is a snippet of the code: require('isomorphic-unfetch') const url = `https://www.instagram.com/graphql/quer ...

Identifying the specific filter used in Vue-tables-2

Trying to configure a basic server-side vue-tables-2 with dual filters - one dropdown and the other a search field. The challenge here is identifying which filter was applied within the requestFunction() in order to send a server request. My current strate ...