Using JavaScript, create SVG illustrations of circle arcs measuring one degree each

I have successfully created a SVG circle using Javascript and now I need to draw 1 degree center line arcs inside the circle.

Currently, I am struggling with the calculation of degrees and iterating through to create filled arcs as shown in the image, but each arc should be exactly 1 degree wide to completely fill the circle.

This is what I have accomplished so far:

var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
    var svgwidth=550, svgheight=550;
    var width = 500, height = 500;
    var x = width/2;
    var y = width/2;
    var r = width/2-10;
    svg.setAttribute("width", svgwidth);
    svg.setAttribute("height", svgheight);
    // create a circle
    const circle = document.createElementNS(
      "http://www.w3.org/2000/svg",
      "circle",
    );
    circle.setAttributeNS(null, "cx", x);
    circle.setAttributeNS(null, "cy", y);
    circle.setAttributeNS(null, "r",  r);
    circle.setAttributeNS(null, 'style', 'fill: none; stroke: blue; stroke-width: 4px;' );
    svg.appendChild(circle);
    
    //Arcs
    var degree = 1;
    var totalArcs = 360;
    var middlePointX = width/2;
    var middlePointY = width/2;
    
    var newLine = document.createElementNS('http://www.w3.org/2000/svg','line');
    newLine.setAttribute('id','line2');
    newLine.setAttribute('x1', middlePointX);
    newLine.setAttribute('y1',middlePointY);
    newLine.setAttribute('x2',100);
    newLine.setAttribute('y2',100);
    newLine.setAttribute("stroke", "black")
    svg.append(newLine);
    
    document.getElementById("div1").appendChild(svg);
<div id="div1">

</div>

View my progress on JS Fiddle

I aim to achieve something similar to the provided image, with each segment filling up precisely by 1 degree.

https://i.sstatic.net/uJjel.png

Your assistance would be greatly appreciated.

Answer №1

No need for complex calculations.

  • The key here is to simply set pathLength=360 on a <circle>, and draw each circle segment with a 1/360 stroke-dashoffset

  • You can draw multiple circles by setting the stroke-dashoffset=N for each one

  • Create it as a native Web Component called <svg-slices> (JSWC supported in all modern browsers)
    and then you just need HTML:

    <svg-slices></svg-slices>
    <svg-slices slices="100"></svg-slices>
    <svg-slices slices="360"></svg-slices>

<style>
  svg-slices {
    width: 180px
  }
</style>

<svg-slices></svg-slices>
<svg-slices slices="100"></svg-slices>
<svg-slices slices="360"></svg-slices>

<script>
  customElements.define("svg-slices", class extends HTMLElement {
    connectedCallback() {
      this.style.display = "inline-block";

      let colors = ["green", "gold","red", "blue", "magenta"];
      let length = this.getAttribute("slices") || colors.length;

      let slice = ( idx , color = colors.shift() ) => {
        colors.push(color); // cycle colors
        return `<circle stroke="${color}"      stroke-dashoffset="${idx}" 
                        pathLength="${length}" stroke-dasharray="1 ${length-1}" 
                 cx="50%" cy="50%" r="25%" fill="none" stroke-width="50%"/>`;
      };
      
      let slices = Array.from({length}, (el, idx) => slice(idx)).join("");
      
      this.innerHTML = `<svg viewBox="0,0,9999,9999">${slices}</svg>`
    }
  });
</script>

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

How to Transfer a Props Value to an External Function in Vue 3

I'm currently working on a page that displays user details and need to also show the invoices associated with that user. <template> <div> <div> // Child component one ..... </div> <div ...

The function of slidetoggle is malfunctioning when clicked

I currently have two dynamic containers with one displaying grouped boxes, quantities, and totals, while the other shows detailed information. Both container values are added dynamically at runtime. By default, the grouping container is displayed on the p ...

Replicating the performance graph of Windows Task Manager

Looking for a JavaScript library that can replicate the dynamic chart seen on the CPU Usage History section of the Windows Task Manager's Performance tab. Any recommendations would be highly appreciated. ...

Working with jQuery: Retrieving the ID of an element that is generated dynamically

Looking for some guidance: I'm working on dynamically creating a table based on the response from an AJAX call. The table includes headers and rows, with new rows added using the "after" function. However, I'm facing an issue with accessing the ...

The alert box is not displaying, only the text within the tags is visible

Trying to implement an alert message for logged-in users. A successful login will trigger a success message, while incorrect username or password will display an error. function showMessage(response) { if (response.statusLogged == "Success login") { ...

Error in scrolling previews detected in Jssor horizontal template maker

I've been working with Jssor Slider Maker and I'm using the vertical preview template that features two columns on the left side and a maximized image on the right side. After pulling the code from the developers pack, it includes scripts, CSS an ...

What is the method for establishing session or cookie in an HTTPS request to a specific URL?

When making an HTTPS GET request in Node.js to a specific URL, it is necessary to include the session cookie. In this case, I already have the value of the cookie that needs to be sent. var URL = require('url-parse'); var appurl = "https://test ...

What is the best way to display long text in a browser alert without it being cut off?

Seeking to display a large amount of data in an alert box, but only a portion is currently visible. The following text is all that can be seen: ["19467,1496257152583","19227,1496256651094","19469,1496257033968","17285, ...

Exploring MongoDB: Filtering Array Elements in a Project

In my current aggregation setup, I am using the following simplified code: Model.aggregate([ { $lookup: { from: 'orders', localField: '_id', foreignField: 'customer', as: 'orders ...

Efficiency levels of reach = within angular instructions

Creating a directive can be done in various ways. Here is an example of how I structured mine: 'use strict'; myApp.directive('mySwitchOnOff', [ '$rootScope', function($rootScope) { return { restrict: 'C' ...

"Trouble arises when attempting to duplicate an array with string indexes using jQuery

I am attempting to duplicate an array named ar, which contains string indexes, into another array called arCopy using jquery. You can view the structure of the array here. Initially, I tried copying arrays like this: var arCopy = ar; However, when I atte ...

Verifying phone numbers with express.js

I am looking to incorporate phone number authentication in my express.js API, similar to apps like WhatsApp or Telegram. While I have experience with passport.js, I haven't come across a strategy specifically for phone numbers. My idea is to generate ...

Host image previews on the server using Dropzone.js

I'm currently utilizing Dropzone.js along with Angular.js for image uploads. However, I haven't been able to figure out a way to upload thumbnails to my server. .dropzone({ url: "/gallery/add", maxFilesize: 100, paramName: "up ...

Achieving nested routes without the need for nested templates

My Ember routes are structured like this: App.Router.map(function() { this.resource("subreddit", { path: "/r/:subreddit_id" }, function() { this.resource('link', { path: '/:link_id'} ); }); }); However, ...

ESLint is not performing linting even though the server is operational

I found a frontend template online and successfully installed all the packages using yarn. However, although I have an .eslint.json file in place and the ESLint extension is installed in Visual Studio Code, I am not seeing any linting errors. Below is the ...

What could be causing my search function to not recognize special characters?

It seems like there might be an issue with character encoding. My JavaScript search function is unable to identify specific strings that contain certain special characters such as parentheses, asterisks, and numbers. The JavaScript code I am using is quit ...

Module 'xhr2' not located

Snippet of code : let XMLHttpRequest = require('xhr2'); let xhr = new XMLHttpRequest(); xhr.open('GET', 'data.json', true); xhr.send(); Issue : internal/modules/cjs/loader.js:969 throw err; ^ Error: Module 'xhr2' n ...

Stop a Post Request from being processed once a form has been submitted to an IFrame

Is there a way to cancel a post after submitting a form to an IFrame? $form = jQuery("<form target='iframetarget' method=post><files...></form>"); $form.submit(); I am looking for a method like $form.cancelPost(); to stop the ...

Steps to trigger an action upon selecting a radio button on an HTML and CSS website

After creating a website with HTML and CSS that allows users to select options using radio buttons, I am now seeking advice on how to implement actions based on their choices. If a user selects an option, I want a specific action to occur, but I am unsur ...

Firebase monitors the authentication status of a user

Trying to maintain a global state in my application based on whether the user is logged in or not has me puzzled. Should I only have a single onAuthStateChanged() in my JavaScript file to monitor state changes and manipulate HTML elements like account deta ...