Step-by-step guide on building an engaging Donut chart using jQuery

After spending several hours working on it, I'm struggling to draw my donut graph with JavaScript. Can anyone provide a solution? I am looking for a way to add 25% when one checkbox is selected and +25% when two checkboxes are selected. Thank you in advance.

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

Answer №1

give this a shot:

JavaScript:

$(document).ready(function () {
var el = document.getElementById('graph'); // access canvas

var options = {
    percent:  el.getAttribute('data-percent') || 25,
    size: el.getAttribute('data-size') || 220,
    lineWidth: el.getAttribute('data-line') || 15,
    rotate: el.getAttribute('data-rotate') || 0
}

var canvas = document.createElement('canvas');
var span = document.createElement('span');
span.textContent = options.percent + '%';
    
if (typeof(G_vmlCanvasManager) !== 'undefined') {
    G_vmlCanvasManager.initElement(canvas);
}

var ctx = canvas.getContext('2d');
canvas.width = canvas.height = options.size;

el.appendChild(span);
el.appendChild(canvas);

ctx.translate(options.size / 2, options.size / 2); // adjust center
ctx.rotate((-1 / 2 + options.rotate / 180) * Math.PI); // rotate -90 deg

//imd = ctx.getImageData(0, 0, 240, 240);
var radius = (options.size - options.lineWidth) / 2;

var drawCircle = function(color, lineWidth, percent) {
        percent = Math.min(Math.max(0, percent || 1), 1);
        ctx.beginPath();
        ctx.arc(0, 0, radius, 0, Math.PI * 2 * percent, false);
        ctx.strokeStyle = color;
        ctx.lineCap = 'round'; // butt, round or square
        ctx.lineWidth = lineWidth
        ctx.stroke();
};

drawCircle('#efefef', options.lineWidth, 100 / 100);
drawCircle('#555555', options.lineWidth, options.percent / 100);

$(".chkBox").on("click", function(){
    var dp = parseFloat($("#graph").attr("data-percent"));
    if($(this).is(":checked")){
        $("#graph").attr("data-percent", dp + 25);
    }else{
        $("#graph").attr("data-percent", dp - 25);
    }
    span.textContent = parseFloat($("#graph").attr("data-percent")) + '%';
    console.log($("#graph").attr("data-percent"));
    drawCircle('#efefef', options.lineWidth, 100 / 100);
    drawCircle('#555555', options.lineWidth, parseFloat($("#graph").attr("data-percent")) / 100);
});
});

HTML:

<div class="chart" id="graph" data-percent="0"></div>
<label for="id_1">A</label>
<input type="checkbox" class="chkBox" id="id_1" /><br/>
<label for="id_2">B</label>
<input type="checkbox" class="chkBox" id="id_2" /><br/>
<label for="id_3">C</label>
<input type="checkbox" class="chkBox" id="id_3" /><br/>
<label for="id_4">D</label>
<input type="checkbox" class="chkBox" id="id_4" />

CSS:

div {
    position:relative;
    margin:80px;
    width:220px; height:220px;
}
canvas {
    display: block;
    position:absolute;
    top:0;
    left:0;
}
span {
    color:#555;
    display:block;
    line-height:220px;
    text-align:center;
    width:220px;
    font-family:sans-serif;
    font-size:40px;
    font-weight:100;
    margin-left:5px;
}

input {
    width: 200px;
}

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

Steps for removing an item from an array in MongoDB

Is it possible to remove an object from the mainList array? _id:ObjectId("5fafc5aec2b84c301845c55a"), username:"test", mainList:[ { _id:ObjectId("5fafdf1a5b49510c789af0ae"), n ...

What is the best approach to decrease the size of a button in HTML and CSS when the text size is also reduced?

Check out this code snippet! I'm new to coding, so let me know if you see any errors or ways it could be improved. button { font-size: 10px; font-family: roboto, Arial; color: white; background-color: rgb(59, 102, 241); border-radius: 100p ...

Guide on enabling the scrollbar within a text area while utilizing the pointer-events: none property

After applying the CSS rule pointer-events: none to the text area, I noticed that the scrollbar was disabled. I need the scrollbar to remain enabled so that users can scroll and view the entire content, while still preventing editing within the textarea u ...

Utilizing React JS Styled-Components to Import Images from the Public Directory

I've been attempting to set the image as a background-image from the public folder using styled-components. I've tried the following: import styled from "styled-components"; import Background from 'process.env.PUBLIC_URL + /images/ ...

Let the numerical tally commence once we arrive at said juncture

Our script is designed to count numbers, but the issue arises when the page is refreshed and the number count starts over. We want the count to start only when a user reaches that specific number or point. Css:- .office{padding-right: 5px; padding-left: ...

Dispatch prop within useEffect

App.js -> <Lobbies inGame={inGame} setLobby={setLobby} userName={userName} userKey={userKey}/> Lobbies.js -> import React, { useState, useEffect } from 'react'; import firebase from 'firebase'; const Lobby = ({userKey, ...

What is the reason for encountering the error message "Property 'floatThead' does not exist on type 'JQuery<any>' when trying to use floatThead in Angular/TypeScript?

For my project, I am incorporating the third-party jQuery library called https://github.com/mkoryak/floatThead. To work with Bootstrap and jQuery, I have installed them using NPM through the command line. Additionally, I have used NPM to install floatThea ...

Competition among fetch requests

I am currently developing a tracker that is designed to gather data from our clients' websites and send it to our API using fetch requests when site users navigate away from the page. Initially, I planned to utilize the beforeunload event handler to ...

Tips for preventing a promise from being executed more than once within an observable while being subscribed to a BehaviorSubject

I've defined a class called Store with the following structure: import { BehaviorSubject, Observable } from 'rxjs' export abstract class Store<T> { private state: BehaviorSubject<T> = new BehaviorSubject((undefined as unknown ...

Stop unwanted scrolling upwards by using jQuery ajax function $.load

I'm currently in the process of creating an ajax chat using jquery and php. Everything seems to be running smoothly except for one issue related to scrolling. Essentially, I've implemented a time-out function that automatically reloads the inner ...

Achieving left alignment for Material-UI Radio buttons: Float them left

Click here to view the demo https://i.stack.imgur.com/Yt4ya.png Check out the demo above to see the code in action. I'm currently struggling to align the radio buttons horizontally, wondering if there's an easier way to achieve this using Mater ...

resetting dropdown selections upon page refresh using jQuery and AJAX

Is there a way to reset or clear the values of two select boxes after refreshing the page in CodeIgniter? Currently, both select boxes retain their values after a refresh. Below is the code I am using: <?php echo form_dropdown('cat_id', $ ...

Getting input elements with Puppeteer can be done by waiting for the page to fully load all elements within the frameset tag

Seeking to gather all input elements on this website: This is how the element source page appears. Below is my code snippet: const puppeteer = require("puppeteer"); function run() { return new Promise(async (resolve, reject) => { try { ...

Error when spaces are present in the formatted JSON result within the link parameter of the 'load' function in JQuery

I am facing an issue with JSON and jQuery. My goal is to send a formatted JSON result within the link using the .load() function. <?php $array = array( "test1" => "Some_text_without_space", "test2" => "Some text with space" ); $json = jso ...

The HTML link is not directly attached to the text, specifically in Internet Explorer

When viewing my website in Chrome, the menu links in the Header function correctly. However, in Internet Explorer (specifically version 11), hovering over 'HOME,' 'LISTINGS,' or 'AGENTS' reveals that the displayed URL is incor ...

Is there a way to alter the color of radio buttons?

Is there a way to use CSS to change the background color of a radio button? I've searched online, but all the solutions I found involve JavaScript, which I don't fully understand. I attempted this CSS code, but it didn't have the desired eff ...

Another query has arisen about the html5 dtd/schema

How can we validate HTML5 documents for syntax accuracy and structural soundness if there is no DTD or schema? It's crucial for our industry to have a reliable method of ensuring validity. The W3C's online validation tool is helpful for individua ...

Vue email validation is failing to return a valid email address

I'm relatively new to Vue and have implemented email validation using the reg expression in my Vue script data for this project. By utilizing console.log(this.reg.test(this.email)) and observing the output while users input their email, the validation ...

Is there a way to set the background of the first sibling element to blue, but change it when another sibling element is hovered over?

I have a list of names: <div>Timothy Gruns</div> <div>Lawrence Fishly</div> <div>Jackson Crolya</div> What I want is for the background color to change to blue when any name is hovered over. However, if no names are be ...

PHP link malfunctioning

Recently, I have been working on adding links to new pages in PHP using Panique for authorization. You can find more information about Panique here. In the views directory, I created a new page called product-des.php. However, when I tried to add a link f ...