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

What is the best way to eliminate products that have already been utilized?

Take a look at my code snippet. $(function() { $("#tags input").on({ focusout: function() { var txt = this.value.replace(/[^a-z0-9\+\-\.\#]/ig, ''); // only allow certain characters if (txt) $("<span/& ...

Encountered the error message "Router.js file throwing a TypeError: next is not a function" while implementing navigation guards in my Vue 3 project

I'm puzzled as to why 'i' doesn't recognize the next function, even though I followed a similar video that implemented it without any errors. import Dashboard from "./Pages/Dashboard.vue"; import Customers from "./Pages/Customers.vue"; ...

Parsing improperly formatted JSON from an HTTP GET request can be done using either AngularJS or JQuery

Trying to decipher a poorly formatted JSON response from a remote server that looks something like this: //[ {},{} ] In my AngularJS code: $http.get('http://www.example.com/badjson') .success(function(data) { console.log(data); }) ...

Attempting to decode JSON data

I'm new to node.js and trying to learn how to send a JSON object using REST. However, I keep getting an error message that says "SyntaxError: Unexpected token  in JSON at position 0". I've checked the JSON using an online validator and it seem ...

When should CSS compression and combining / JS minification be performed - at runtime or during build time?

I need to find a way to compress, version (for caching reasons), and possibly combine our JS and CSS files. I've come across two main approaches so far: 1) During the build process: Using an MSBuild task or similar. 2) Dynamically at runtime: Through ...

`In NestJS Nested Schema, the @Prop decorator and mongoose options are not applied as expected

I'm currently working on constructing a Schema that includes a nested object. I am trying to define default values and required properties within the nested object, but it seems like the options I set are being ignored. task.entity.ts @Schema() expor ...

Utilizing Zustand state management with Next.js 13.4.12 for routing and server-side rendering, enhanced with local storage

My Zustand store code looks like this: import create from "zustand"; import { persist } from "zustand/middleware"; const useProjectStore = create( persist( (set) => ({ selectedProject: null, setSelectedProject: (pr ...

What is the best way to update the div id by extracting the last digits from a number?

Is there a way to change the div ids using a function? Before: <div id="a_1">a1</div> <div id="b_1">b1</div> <div id="c_1">c1</div> <div id="d_1">d1</div> <button onclick="change()">Change</button& ...

Tips for customizing the time selector in material-ui-time-picker

Is there a way to enable keyboard input control for the material-ui-time-picker? Currently, it only allows editing when clicking on the clock interface. Here is a snippet of my code: import React, { Component } from "react"; import { TimePicker } from " ...

Encountering a Next.js installation error due to the inability to locate the module fs

Having trouble with the installation of a new Next.js 14 app. I've searched on Google and Stack Overflow but haven't been able to find a solution. I'm stuck at this point. Can anyone offer some assistance? What I have attempted: npx creat ...

Utilize the key-value pair from ng-repeat to expand the scope of the expression

In an attempt to utilize the key value from ng-repeat as an extension of another scope.arrayResult, I aim to achieve arrayResult.q1/q2/q3 etc... <ul ng-repeat="(key,x) in data"> <li><h4>Question: {{x}}</h4> <p>{{ ar ...

Steps to develop a runnable Express API

After developing a basic yet fully functional Node.js Express API application using JavaScript, I am now looking to convert it into an executable file that can be run on Windows systems. The main reason behind this is to provide clients with the option of ...

Struggling to find a solution for your operating system issue?

We are currently attempting to utilize the markdown-yaml-metadata-parser package for our project. You can find more information about the package here. Within the package, it imports 'os' using the following syntax: const os = require('os ...

What could be the reason for the undefined value of my ID retrieved from the next JS router.query upon page refresh?

When using the id obtained from the next router.query to dynamically render elements, it works fine when accessing the room from next/link. However, upon refreshing the page, an error is thrown. https://i.stack.imgur.com/yEjGS.png Below is the code snipp ...

Extracting JSON Data into Text Boxes within jQuery UI Dialogs

Let me provide some context to my current issue. Due to the nature of the problem being work-related, I am unable to share much of the code. The task at hand involves working with a jQuery dialog. Essentially, I have a list of names displayed with a boots ...

Exiting a void method in JavaScript/Typescript using the return or break statement

I find myself dealing with a complex method in Typescript that contains multiple if else if else constructs. It's a void method, and I'm wondering how I can exit the method based on a specific if condition without having to execute the remaining ...

Concealing Popover with internal click

I am currently implementing Vue-PopperJS in my project, following the setup provided on the linked page with a few modifications: <template> <Popper ref="popover" trigger="clickToToggle" :options="{ pla ...

Retrieve key-value pairs from a database and store them as variables in PHP before transferring them into an array in JavaScript

My challenge lies in loading Chinese characters as keys and their English translations as values from a database into a PHP array, so that I can use them on the client side in JavaScript. The process involves fetching key:value pairs from PHP into a JavaSc ...

What is the best way to seamlessly transition layers from one location to another as the mouse exits and re-enters the window?

I have been working on refining a parallax effect to achieve a seamless transition between two positions based on where the mouse exits and enters the window. In the JSFiddle example provided, there is a slight 'pop' that I am looking to replace ...

What is the best way to assign user input to my JavaScript variables?

As a newcomer to programming, I am eager to develop an app that utilizes the numerical values inputted by customers as variables for calculations. How can I extract the value from an input using JavaScript? For instance, how can I subtract one input value ...