What could be causing my randomly generated value to be overwritten so quickly?

I'm encountering an issue with my code. I am attempting to generate objects in random locations using drawHyperBall(), getRandomIntX(), and getRandomIntY(). However, the random value seems to be constantly overwritten. How can I resolve this problem?

See the code below:

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x = canvas.width/2;
var y = canvas.height/2;
var ballRadius = 40;
var hBallRadius = 10;
var w = 5;
var hunger = 630;
var hypo = 0;
var hyper = 0;
var randomX;
var randomY;
var Keys = {
    up: false,
        down: false,
        left: false,
        right: false
};

function drawBall() {
    ctx.beginPath();
    ctx.arc(x, y, ballRadius, 0, Math.PI*2);
    ctx.fillStyle = "#00FF00";
    ctx.fill();
    ctx.lineWidth= 3.5;
    ctx.stroke();
    ctx.closePath();
}

function drawConceBar() {
ctx.strokeRect(100,930,630,30)
}

function drawHungerBar() {
ctx.fillStyle = "#73591C";
ctx.fillRect(1140,930,hunger,30)
ctx.fillStyle = "black";
ctx.strokeRect(1140,930,630,30)
}

function drawTitle() {
ctx.fillStyle = "black";
ctx.font = "120px Arial";
ctx.fillText("Osmos.is",canvas.width/2 -210,120);
}
function drawBorder() {
ctx.strokeRect(100,150,1670,730);
}

function getRandomIntX(minX,maxX) {
    return Math.floor(Math.random() * (maxX- minX + 1)) + minX;
}
function getRandomIntY(minY,maxY) {
    return Math.floor(Math.random() * (maxY - minY + 1)) + minY;
}

function drawHyperBall() {
ctx.beginPath();
    ctx.arc(getRandomIntX(110, 1660), getRandomIntY(160, 720), hBallRadius, 0, Math.PI*2);
    ctx.fillStyle = "#FF0000";
    ctx.fill();
    ctx.closePath();
}

function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);

drawBall();

drawBorder();

drawTitle();

drawConceBar();

drawHungerBar();

if(y > 830) {
    y -= 5;
}
else if(y < 195) {
    y += 5;
}

if(x < 150) {
x += 5;
}
else if(x > 1720) {
x -= 5;
}

if (Keys.up) {
    y -= 5;
}
else if (Keys.down) {
    y += 5;
}

if (Keys.left) {
    x -= 5;
}
else if (Keys.right) {
    x += 5;
}

if (hunger <= 0) {
hunger += 1;
}
else {
hunger -= 1;
}
}

window.onkeydown = function(e) {
    var kc = e.keyCode;
    e.preventDefault();
    if      (kc === 37) Keys.left = true;  
    else if (kc === 38) Keys.up = true;    
    else if (kc === 39) Keys.right = true;
    else if (kc === 40) Keys.down = true;
};

window.onkeyup = function(e) {
    var kc = e.keyCode;
    e.preventDefault();
    if      (kc === 37) Keys.left = false;
    else if (kc === 38) Keys.up = false;
    else if (kc === 39) Keys.right = false;
    else if (kc === 40) Keys.down = false;
};

setInterval(draw, 10);
setInterval(drawHyperBall, 1000);
<canvas id="myCanvas"></canvas>

Answer №1

After some investigation, I successfully identified the root cause of the issue. Instead of clearing the entire canvas, I implemented a new function that targets specific elements for deletion.

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

Component inexplicably rendering multiple times

After encountering multiple re-renders in my code, I decided to comment out every line and discovered that the constant definition was causing the issue: const MyComponent = () => { console.log('render') // logs 4 times const myRef = useR ...

The req.isAuthenticated function in Node.js passport consistently returns false

I have encountered a problem with my authentication node.js app that I haven't been able to solve despite researching similar questions and trying various solutions. My application consists of a front end in react-native and a MongoDB database, and I ...

Is there a way to upload a kml file to Google Maps using my website or by using JavaScript commands?

I have information on my website regarding gas stations, including the quality of gasoline and the GPS coordinates of each station. My concept involves incorporating Google Maps into my site, similar to how flightradar24.com displays pins indicating gas s ...

Aligning a child div within a parent div using HTML/CSS where the child div takes up 30% of the parent div and

Can anyone help me figure out why these two INPUT elements aren't aligning next to each other? I appreciate any assistance you can offer! <STYLE> html, body { width: 100%; height: 100%; margin: 0px; padding: 0px; } </STYLE& ...

Is jQuery utilized by the bootstrap-grid system?

Finale: In our current setup, we are utilizing Angular 9, and like many frontend frameworks, there is a preference against incorporating other JavaScript libraries alongside the framework for manipulating the DOM. The Challenge: I am hesitant to include ...

Background Image Division (Twitter Bootstrap)

I am facing a challenge while creating a module with a span8 width and varying height. The div contains an image that dictates its height, with text overlaid on the image. My issue lies in preventing part of the image from getting cropped when Bootstrap re ...

Adjust the date input alignment in mobile browsers

I am trying to align the entered date to the left in input[type='date']. However, when testing on mobile browsers like safari and chrome, the date remains centered within the input. mobile example This is the code I have been working on: .co ...

Enable and disable subscriptions in real-time to control the amount of cached data and prevent the error message "Uncaught TypeError: Converting circular structure to JSON"

In an attempt to control the cache on the client side, we had the idea of toggling the subscription to a specific Collection on and off by placing the Meteor.subscribe call within a reactive context as recommended in the Meteor documentation - "In addition ...

Tips on adding an image using Reactjs

I am currently working in Reactjs with the Next.js framework. I am attempting to upload images using Axios (POST method API) and will be utilizing an "api in PHP". Could someone please guide me on how to achieve this? I have tried the code below, but it&ap ...

What steps can be taken to ensure express Node.JS replies to a request efficiently during periods of high workload

I am currently developing a Node.js web processor that takes approximately 1 minute to process. I make a POST request to my server and then retrieve the status using a GET request. Here is a simplified version of my code: // Setting up Express const app = ...

What's causing all my carousel slides to stack on top of each other instead of presenting in a

Whenever I click 'run' or 'preview' in a browser, specifically using Chrome, all three slides are displayed stacked from 1 to 3 in a static view. They do not toggle through each slide as intended. This issue only occurs on Codeply, a p ...

How to use JavaScript and regex to control the state of a disabled submit button

I have a challenge where I need to activate or deactivate a submission button in a form called btn-vote using JavaScript. The button will only be activated if one of the 10 radio buttons is selected. Additionally, if the person-10 radio button is chosen, t ...

Impact on adjacent div

Within my code, I have two sibling divs that contain additional nested divs as shown below: <div class="btn_lists"> <div class="btn green_btn"> <img src="<?= asset_url() ?>images/escolar_07__1.png" /> </div> & ...

Unlock the Power of Sockets in JavaScript and HTML

How can I work with sockets in JavaScript and HTML? Could HTML5 features be helpful? Are there any recommended libraries, tutorials, or blog articles on this topic? ...

"Create a Vue element containing a trio of buttons each displaying a distinct numeral

I am currently dealing with a component that generates three items (boxes) each containing three buttons (created using v-for). The issue I am facing is that when I click on a button, all the numbers inside the buttons change simultaneously. I want to be a ...

I just finished crafting a dynamic line chart with d3.js within a React environment. However, I am now looking to add some personalized touches to enhance its appearance. Could you kindly review the details and code

I want to create a line chart using React and D3, similar to the one depicted in this image. Presently, I have partially implemented the chart with the code provided below. You can see it here. The code snippet I've developed so far is outlined as f ...

The Struggle with Bootstrap Accordion

I'm currently in the process of learning bootstrap. I copied the code for the 'Flush' Accordion from the bootstrap docs, but my version looks completely off. Despite linking the CSS stylesheet and JS Bundle, it doesn't seem to align pro ...

Changing the name of a file using NPM

Is there a way to change the name of a specific file in npm scripts? I need to modify files for distribution, but they must have different names than the original... I attempted using orn, however it only works on the command line and not as an npm script ...

"Navigate with ease using Material-UI's BottomNavigationItem and link

What is the best way to implement UI navigation using a React component? I am currently working with a <BottomNavigationItem /> component that renders as a <button>. How can I modify it to navigate to a specific URL? class FooterNavigation e ...

What is the process for changing the background color when a button or div is pressed, and reverting the color back when another button or div is

Looking to customize a list of buttons or divs in your project? Check out this sample layout: <button type="button" class="btn" id="btn1">Details1</button> <button type="button" class="btn" id="btn2">Details2</button> <button ty ...