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

Is there a way to update the background image of a div element through a JavaScript file within a react component?

After spending hours on this issue, I am still stuck and have exhausted all my ideas and research. In my project, I have three buttons that are supposed to change the background image of my site. The background image is linked to the default "App" div elem ...

Issue encountered with AJAX request using JavaScript and Express

I'm brand new to this and have been searching online for a solution, but I can't seem to figure it out. It's possible that I'm making a basic mistake, so any assistance would be greatly appreciated. I'm trying to create a simple f ...

The XML information vanished during the transformation into JSON format

After converting XML to JSON using multiple conversion libraries, I noticed that the property name attributes and Item name attributes were lost. Why is this happening? Does anyone have suggestions on how I can modify my XML to make it more compatible for ...

The transition from ExtJS 4 to ExtJS 5: A comprehensive guide

We're in the process of transitioning a web application from ExtJS 4 to ExtJS 5. Upon testing the index.html, we encountered an error message (displayed in the Firefox-FireBug-console): NetworkError: 404 Not Found - http://localhost:8080/ext/build/e ...

Executing certain test suites with defined capabilities in Protractor

My website is designed to be compatible with both desktop and mobile browsers, each having its own unique user interface. In my protractor config file, I have some suites that need to be tested using the desktop user agent, while others require testing usi ...

Utilizing util.format to enclose every string within an array with double quotation marks

Currently .. var utility = require("utility"); var carsInput = 'toyota,chevrolet'; var cars = carsInput.split(','); var queryString = utility.format('Cars: [%s]', cars); console.log(queryString); // Cars: [toyota,chevrolet] ...

Comprehending the positioning of elements enclosed within a parent <div> tag

I'm struggling to understand why: vertical-align - isn't behaving as expected in this scenario, even though the elements are aligned along a baseline and are inline elements. I've experimented without using float but that didn't sol ...

There are no markers or popups currently displayed on the map

Utilizing the ngx-leaflet plugin for leaflet, I have established the base layers and integrated a listener for the leafletMapReady event. Within my handler, I attempted to add both a marker and a customized popup. The handler code is displayed below: init ...

Troubleshooting the issue of "Mismatched transaction number*" in MongoDB and Node.js

While trying to add data, I encountered an issue with modifying two schemas using ACID transactions in MongoDB with Node.js. Upon running the program, an error was displayed: (node:171072) UnhandledPromiseRejectionWarning: MongoError: Given transaction n ...

Pagination does not refresh when conducting a search

HTML Code: The following HTML code displays a table with a search filter. . . <input type="search" ng-model="search.$" /> <table class="table table-striped table-bordered"> <thead> <tr> <th><a href ...

Checkbox acts like radio buttons in JavaScript

Currently, I have a unique setup where a table is generated dynamically based on the user's selection from a dropdown. Within this table are three checkboxes per row, with a limit of 2 checkboxes that can be checked per row. The behavior of Checkbox ...

Content on the right floating underneath content on the left

Here is the HTML code snippet I am working with: <div id="main_content"> <div id="left_side> <h1> MY BIG HEADER </h1> </div> <div id="content_area"> SOME CONTENT HERE SOME CONTENT HERE S ...

Using DraftJS to swap text while preserving formatting

Currently, I am implementing Draftjs with draft-js-plugins-editor and utilizing two plugins: draft-js-mathjax-plugin and draft-js-mention-plugin My goal is to replace all mentions with their corresponding values when the user uses '@' to mention ...

Using $stateParams injection for unit testing Angular applications with Karma

Here is the starting point for the controller code: angular .module('hc.hotelContent') .controller('NameLocationController', nameLocationCtrlFn); //Todo change hotelDataService nameLocationCtrlFn.$inject = ['$stateParams', &a ...

Is it possible to utilize Vue's splice method within a forEach loop in order to delete multiple elements at

I am currently working on an image grid in array form. I am trying to implement a multi-deletion functionality. When a checkbox for each image in the grid is checked, I store the selected image's index in an array called selectedImages. Upon clickin ...

Issues with Swiper functionality in Jquery Mobile

I have implemented the Swiper plugin by idangero.us along with jQuery Mobile... In this case, I am utilizing the Scroll Container Swiper for a content slider... However, I am encountering several difficulties when trying to integrate the code... You can ...

Expanding the MatBottomSheet's Width: A Guide

The CSS provided above is specifically for increasing the height of an element, but not its width: .mat-bottom-sheet-container { min-height: 100vh; min-width: 100vw; margin-top: 80px; } Does anyone have a solution for expanding the width of MatBott ...

Exploring HTML Data with Python String Manipulation

My goal is to use Python to dynamically extract data from an HTML page that is constantly changing. I have identified that the specific data I am interested in is located between a tag that resembles 'abcd>' and another tag. For example: abcd& ...

Can someone guide me on the proper implementation of the 'useEffect' hook in React version 18?

I'm currently working on a project following a YouTube tutorial that uses React 17, while I'm using React 18. Everything has been going smoothly so far, but I've hit a roadblock with formatting animated text. The specific task I'm stuck ...

When elements are arranged side by side without using floats, the alignment at the top is not correct

I am having trouble aligning multiple divs next to each other using inline-flex. They are not lining up properly on top (refer to the screenshot). Interestingly, if I remove the svg, the divs align correctly. ...