Creating a circular shape with a radius that can be adjusted

I'm trying to create an expanding bubble-like circle of various colors when clicked on a blank page. The circle should continue increasing in size each time it is clicked, only stopping when the mouse click is released. I am looking to use HTML, CSS, and JS for this effect. Any suggestions on how I can achieve this?

Answer №1

One way to create a circular animation on a webpage is by utilizing the canvas element along with the getContext('2d') method. Below is a breakdown of how you can achieve this effect:

// Access canvas element
const canvas = document.getElementById('circle');
// Initialize canvas context if available
const ctx = canvas?.getContext ? canvas.getContext('2d') : null;

// Set initial radius and modify the radius
let R = 0;
let modR = 0;

// Function to draw the circle
const draw = (ctx, mod) => {
    // Check if canvas context is properly initialized
    // Display error message and return if not
    if(!ctx) return console.error("Can't get canvas context");
    
    // Stop the animation if the modification falls within certain bounds
    if(
        mod == "inc" && modR <= R ||
        mod == "dec" && modR >= R
    ) return;

    // Increment/decrement the radius by 0.5 units
    // Adjust this value to alter animation speed
    if(mod == "inc") R += 0.5;
    if(mod == "dec") R -= 0.5;

    // Calculate position
    let X = canvas.width / 2;
    let Y = canvas.height / 2;

    // Clear previous circle
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // Draw new circle
    ctx.beginPath();
    ctx.arc(X, Y, R, 0, 2 * Math.PI, false);
    ctx.fillStyle = '#FF0000';
    ctx.fill();

    // Attempt to animate resizing
    requestAnimationFrame(() => draw(ctx, mod));
}

// Function to increase the circle size
const inc = r => {
    // Ensure the enlarged circle fits within the canvas area
    // Return if it exceeds the limits
    if(canvas?.width && modR * 2 >= canvas.width) return;

    // Increase the total radius
    modR += r;

    // Update circle size with increase mode
    draw(ctx, "inc");
}

// Function to decrease the circle size
const dec = r => {
    // Ensure the reduced circle size is not too small
    // Return if it goes below a certain threshold
    if(modR * 2 <= 10) return;

    // Decrease the total radius
    modR -= r;

    // Update circle size with decrease mode
    draw(ctx, "dec");
}
body {
    text-align: center;
}
<html>
  <head>
    <meta charset=utf-8 />
    <title>Draw a circle</title>
  </head>
  <body onload="inc(5);">
    <canvas id="circle" width="150" height="150"></canvas>
    <div class="btn">
      <button onClick="inc(5);">Increase</button>
      <button onClick="dec(5);">Decrease</button>
    </div>
  </body>
</html>

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

Having troubles with Navbar svg images not loading on certain pages on the express/ejs app?

Hello there, I'm encountering an issue with my navbar in an express app. The navbar is saved as a partial and included in a boilerplate wrapper used on most pages. Here's a snippet of how it looks: <h1>HELLO<h1> Within the boilerplat ...

Necessary within a JavaScript Class

As a newcomer to using classes in JavaScript, I've been exploring the best practices and wondering about how 'requires' work when used within a class. For example, let's say I want to craft an IoT Connection class for connecting to the ...

Making numerous changes to a single field in mongoDB can result in the error message: "Attempting to edit the path 'X' will generate a conflict at 'X'."

Looking to streamline my update operation: private async handleModifiedCategoryImages(data: ModifiedFilesEventData) { this.categoryModel .findByIdAndUpdate(data.resourceId, { $pullAll: { images: data.removedFiles || [] } ...

Looking for a resolution with NicEditor - Seeking advice on incorporating custom select options

I recently started using NICInline Editor and found a helpful sample at Is there a way to incorporate custom options into this editor? I would like the selected option's value to be inserted right at the cursor point of the Editor Instance. Query: H ...

Sending information across React context

I've encountered a challenge when trying to transfer data from one context to another in React. The job data I receive from a SignalR connection needs to be passed to a specific job context, but I'm unsure of the best approach for achieving this. ...

The browsers Firefox and Internet Explorer are unable to perform ajax requests

Currently, I am utilizing jQuery version 3.3 in conjunction with the following Ajax script: <script type="text/javascript"> $(document).ready(function(){ $("form").submit(function(){ $.ajax({ url: 'msgs.p ...

Eliminate any additional spacing within the pre/code tags

I am currently utilizing prism.js for code highlighting. I have encountered an issue where there are unnecessary white spaces at the top and bottom of my output. You can view a live example here. <pre> <code class="language-css"> &lt ...

Generate rows based on the quantity of items in Django templates

My current goal is: To create a <div class="row-fluid center"> and only display a maximum of 3 elements from list.dias.all. However, I am struggling to come up with the correct code. <div class="row-fluid center" id="{{list.dias.all.count ...

What is the most efficient way to implement OR conditions in JavaScript for shorter code

Hello there! I have a question about optimizing conditions in code. Is there a more elegant way to write the following conditions? state === 'su' || state === 'ja' || state === 'fa' I was thinking if it could be simplified ...

Can the selected week be highlighted along with the corresponding week number in a row?

Can we display the number of the week in a row along with the selected week, either in the toolbar or somewhere else? I attempted to utilize ToolbarComponent, but it overrides the entire header. However, I would like to keep it as is and just add informat ...

IE11 encounters an error labeled SCRIPT1010, signaling an expected Identifier when compiled

Lately, I've been encountering a strange issue in Vue.js. Here's the thing: my application runs smoothly on all browsers locally (yes, even IE 11). But when I compile it using npm run build and deploy it to my server (which essentially serves con ...

Looking for a seamless way to convert jsp code to html using sightly in AEM 6.1?

I need help transforming JSP code to HTML using Sightly in AEM. In the JSP code, we have a scriptlet that stores a value from the dialog into a JSP variable called "coltype" using the code pageContext.setAttribute("coltype", xssAPI.filterHTML(properties. ...

Assign a value to an Html.HiddenField without tying it to the model upon form submission

I have two classes, SubsidiaryClient and Client, that are related in a one-to-many manner as depicted below. Currently, I am utilizing MVC 5 for development. In the Create SubsidiaryClient page, to retrieve the ClientID, you need to click on the browse bu ...

Error message: "The variable _ is not defined when trying to use angular-google-maps library"

I'm encountering an issue where I'm receiving a ReferenceError: _ is not defined while using the angular-google-maps I'm puzzled as to why this error is occurring, as I believe I am following the instructions provided on the website. I hav ...

Does the 'span' element negatively impact the vertical alignment of text?

While working on my code, I noticed an issue with vertical alignment when using span tags to change the background of the text based on its content. The problem occurs specifically when viewing the code in the Android Chrome browser. You can view the initi ...

What is the best way to stop a select menu option from being highlighted once it has been clicked on?

Is there a way to prevent the highlighting of selected options in a <select> menu when a user makes a selection? <select id="my_select_menu"> <option id="1">Option 1</option> // I do not want this option to be highlighted ...

Receive real-time price updates from Next.js using GetServerSideProps data

I'm currently working on fetching live bitcoin prices from CoinGecko. In my index.js file, I have an async GetServerSideProps function that is functioning correctly. The returned props are then passed down to the <Home /> component, and subseque ...

Error encountered in NodeJS after refreshing the node server

I am currently in the process of developing a web application using Node.js, Express framework, and EJS templates. Below is the code snippet for my server setup: const express = require('express'); const app = express(); const PORT = process.en ...

Learn the process of using calc to rotate images on hover with CSS and Jquery

Is there a way to implement the rotate on hover function for images, similar to what is seen on this website under 'our Latest Publications'? I attempted using calc and skew, however, I was unsuccessful in achieving the desired hovering effect o ...

The connection between two arrays remains intact even after using the .push() method in JavaScript or Vue.js

I need help setting up two arrays containing dates. The first array should have the dates in string format, while the second array should contain the same dates but as date objects. methods: { test() { let employments = [ { begin: ...