What is the best way to ensure that the circle is perfectly centered inside the box?

Currently delving into the world of game programming, I've been struggling with this exercise. I can't seem to figure out why the circle won't stop in the center of the box within the update function. What am I missing?

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

var circleX = 100;
var circleY = 100;
var circleR =  50;
var circleC =  'yellow';
var circleSpeedX =  65;
var circleSpeedY =  45;

var rectX = 650;
var rectY = 450;
var rectW = 110;
var rectH = 110;
var rectC = 'red';

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

function drawRect(rectX,rectY,rectW,rectH,rectC)
{
    context.fillStyle = rectC;
    context.fillRect(rectX,rectY,rectW,rectH);
}   

function drawCircle(circleX,circleY,circleR,circleC)
{
    context.fillStyle = circleC;
    context.beginPath();
    context.arc(circleX,circleY,circleR,0,2 * Math.PI);
    context.fillStyle = 'orange';
    context.fill();
}

function update()
{

}

function draw()
{
    clear();
    drawRect(0,0,canvas.width,canvas.height,'black');
    drawRect(rectX,rectY,rectW,rectH,rectC);
    drawCircle(circleX,circleY,circleR,circleC);
}

function loop()
{
    update();
    draw(rectX, rectY, circleX, circleY);
    setTimeout(loop, 30);
}

loop();

Answer №1

Here is the solution you've been searching for: JSFiddle

HTML:

<div>
    <canvas id="myCanvas" height="500" width="500"></canvas>
</div>

JS:

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

var circleX = 100;
var circleY = 100;
var circleR =  50;
var circleC =  'yellow';
var circleSpeedX =  6.5;
var circleSpeedY =  4.5;

var rectX = 200;
var rectY = 200;
var rectW = 110;
var rectH = 110;
var rectC = 'red';

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

function drawRect(rectX,rectY,rectW,rectH,rectC)
{
    context.fillStyle = rectC;
    context.fillRect(rectX,rectY,rectW,rectH);
}   

function drawCircle(circleX,circleY,circleR,circleC)
{
    context.fillStyle = circleC;
    context.beginPath();
    context.arc(circleX,circleY,circleR,0,2 * Math.PI);
    context.fillStyle = 'orange';
    context.fill();
}

    function update()
    {
        if (circleY > rectX && circleX < rectX + rectW &&
            circleY > rectY && circleY < rectY + rectH){
            circleSpeedX = circleSpeedY = 0;
            rectC = 'GREEN';
        }
        else {
            circleX += circleSpeedX; 
            circleY += circleSpeedY;
        }
    }

function draw()
{
    clear();
    drawRect(0,0,canvas.width,canvas.height,'black');
    drawRect(rectX,rectY,rectW,rectH,rectC);
    drawCircle(circleX,circleY,circleR,circleC);
}

function loop()
{
    update();
    draw();
    setTimeout(loop, 30);
}

loop();

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 make a JSONP request using jQuery?

Whenever I try to access this API through the browser, everything works fine and I receive the correct response. However, when I attempt to call the API using jQuery AJAX, I encounter an error. *The script is being refused execution from 'http://api ...

A clever method for implementing lazy-loading using mobx

Can you provide guidance on the most effective way to lazy load properties with MobX? I've been grappling with this issue for a few days now, and I've struggled to find suitable examples ever since strict mode was introduced. While I appreciate ...

Json with ExtJs columns data is fully populated

I am having trouble with displaying columns in my jsp which fetches json data. I am retrieving this json data in my javascript and using Ext.data.JsonStore but the columns are not showing up as expected. Here is the code for the store: store = new Ext.da ...

Personalizing Web Push Alerts (Google Chrome)

I successfully implemented a web push notification for Google Chrome using Google Project and Service Worker. One thing I'm curious about is how to customize or style the push notification. The plain message box doesn't quite cut it for me – I ...

Whenever I attempt to run the NPM install command in the Terminal, it seems to generate multiple errors

I am encountering an issue on my work laptop. I have the latest versions of Angular, Nodejs, Nodesass, and VScode installed in the local environment path. Whenever I download an Angular template from Github and try to do NPM Install, it consistently thro ...

A step-by-step guide on storing JSON data into a variable using NodeJS

Just starting out with Node.js and running into an issue. I need to figure out how to extract and save data from a JSON object retrieved from the GitHub API. var http = require("http"); var express = require('express'); var app = express(); var ...

How can you make the browser window scroll horizontally when a div is clicked using jQuery?

I have an image of an arrow inside a div. The div is positioned fixed in the bottom right corner of an extremely wide page. Is there a way to utilize jQuery to scroll the window 600px to the right each time the arrow is clicked? Also, can I detect when th ...

Ways to replace CSS classes created using makeStyles

To clarify, my development environment is using MUI version 4.12.3. Inside file A, I have a simplified code snippet for a functional component, along with the usage of makeStyles to style a JSX element within the return statement (not displayed here). Ever ...

Creating an AngularJS directive specifically for a certain <div> tag

Recently, I began learning angularjs and came across a script to change the font size. However, this script ended up changing all <p> tags on the entire webpage. Is there a way to modify the font size of <p> tags only within the <div class=" ...

What is the best way to iterate through files within a directory and its nested subdirectories using electron?

I am currently working on developing a desktop application that involves scanning through a directory, including all subdirectories, to locate files containing specific characters in their filenames. Is it feasible to accomplish this task using Electron? ...

Storing Boolean values in MongoDB with Express JS: A Step-by-Step Guide

I am encountering an issue where a Boolean value that I am trying to store in Mongodb always returns false. Below is the schema of my database: const UserSchema = new Schema({ name: String, password: { type: String, required: true }, isAdmi ...

Babeljs encountered an error: TypeError - The super expression should be a function or null, not undefined

Currently, my project involves implementing multiple-files inheritance in ES6 using Node.js and Babel. Babel is used to convert the ES6 code to ES5 since Node does not fully support ES6 yet. Import/export statements are used to connect the different files ...

Create a directive for AngularJS that utilizes SVG elements without using the deprecated

I rely heavily on directives for creating and manipulating intricate SVGs. With the deprecation of "replace" in directive factories starting from version 1.3.??, I am facing a dilemma on how to construct a valid SVG without utilizing replace: true in my di ...

custom checkbox is not being marked as checked

I've been attempting to customize my checkboxes, following various tutorials without success. Despite trying multiple methods, I still can't get the checkboxes to check or uncheck. Here is the code I have so far: https://jsfiddle.net/NecroSyri/ ...

Issue with React: Reading the 'pathname' property from undefined is not possible

I can't figure out why this error keeps popping up. My goal is to create animated transitions between Routes. Can anyone point out where I went wrong? view image description here I tried reinstalling the react-spring package but it didn't solve t ...

Struggling with dragging Vue.js modals?

I am currently utilizing the vue-js-modal library, and I'm encountering an issue with it. Whenever I set my modal to be draggable by using :draggable="true", I can drag it around but then I am unable to input any text in the form fields. It seems to c ...

The webpack vue-loader throws an error message stating "unexpected token {" when processing a single-page .vue component

As a C# backend developer, I am venturing into the world of Vue.js. I typically work with Visual Studio 2017 + ASP.NET MVC (using it as an API + one layout) + Vue.js + Webpack. .vue single-page component files are loaded by vue-loader, while .js files a ...

What are the differences between performing a search in MongoDB (database component) and Node.js (server-side)?

1) My input consists of a string with approximately 30 comma-separated elements, such as str1, str2, str3, etc. This is represented by "INPUT_STRING". 2) Within my MongoDB collection, I have a set of "allowed_strings" which includes entries like str1, str ...

Identify and emphasize fields that contain identical, non-empty values

I am attempting to compare the values of textboxes and highlight them if they are the same, excluding any textboxes that are empty. Feel free to view an example on this JSFiddle link: http://jsfiddle.net/qjqa1et2/61/ Below is the jQuery code I am current ...

What ways can I leverage JavaScript to convert a provided array into multiple different arrays?

I am in need of a function that meets the following criteria: Given the dimensions of an array, return all possible combination arrays based on the given numbers. The length of the given array should be equal to the length of the array returned. The size ...