Create a Bootstrap-compatible responsive doughnut chart using Chart.JS that spans the full width of the

I am utilizing the Angular.js version of Chart.js, although the core functionality remains consistent.

Currently, I have a basic doughnut chart placed inside a responsive Bootstrap container:

<div class="row">
    <div class="col-xs-8">
       <div class="chart-container">
          <canvas id="doughnut" 
                  chart-data="data" 
                  chart-labels="labels" 
                  chart-options="mainDonut" 
                  class="chart chart-doughnut">
          </canvas>
       </div>
    </div>
</div>

The controller options for this setup are as follows:

 $scope.mainDonut ={
    percentageInnerCutout : 90,
    responsive: true
}

Apparently, the chart's width is restricted to match the height of the div container, which is somehow set at around 300px by ChartJS. This results in the following rendering:

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

I aim to make the height adapt dynamically based on the width of my .col-xs-8, completely filling the entire div container. While I am aware that I could achieve this using JavaScript events for window resizing, I prefer to explore other solutions to avoid such scripting if possible.

Any suggestions or alternative approaches would be greatly appreciated?

Answer №1

To ensure responsiveness while maintaining aspect ratio, there are two key considerations:

1) Update the options object with the following properties:

{
   responsive: true,
   maintainAspectRatio: true, 
}

2) Specify the aspect ratio by defining both the width and height attributes for the canvas element. In this scenario, they likely have the same value:

<canvas id="doughnut" 
    width="100"
    height="100"
    chart-data="data" 
    chart-labels="labels" 
    chart-options="mainDonut" 
    class="chart chart-doughnut">
</canvas>

Answer №2

The width of the chart seems to be constrained by the height of the div container, which ChartJS is setting at around 300px inexplicably.

This is actually the default width of the canvas element (http://www.w3.org/TR/html5/scripting-1.html#the-canvas-element).

It appears that the responsive option is not functioning as intended. This could be due to the fact that the parent element lacks a measurable size when the chart is initialized. In Angular, this often occurs when the wrapping elements are not fully rendered at initialization (e.g., due to an ng-show or being within a hidden tab).

CSS styling on the parent element might also be causing issues - although based on your markup, this seems less likely.


Keep in mind that even if you do not manually resize the chart on window resize, Chart.js will automatically adjust it for all responsive charts.

Answer №3

function generateChart() {
    var canvas = document.getElementById('chart-canvas');
    canvas.width = container.offsetWidth;
    canvas.height = container.offsetWidth; ... 
}

+css container block {
   width: 100%;
   min-height: 300px;
}

Trust this information proves useful to you.

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

Creating Test Cases for Service Response Validation

I am currently attempting to unit test an API within my ngOnInit method. The method is responsible for making a call to the service in order to fetch details. If the details are not undefined, an array called 'shoeDataResponse' of type *shoeData ...

Validating Credit Card Numbers with Spaces

Currently, I am in the process of creating a credit card form that requires validation using checkValidity to match the specific card pattern that is dynamically added to the input field. For example, if a user enters a Mastercard number such as 545454545 ...

What is the easiest method to stop text from wrapping around an icon within a bulleted list?

Imagine having rows filled with various icons, each one being quite large. <li><i class="bi bi-patch-check-fill icon-green" style="font-size:40px;"></I>Some text about whatever</li> <li><i class="b ...

Utilizing JSON data to power autocomplete options in textboxes

This answer is similar to my current project. I am building upon the original Plunker and creating a new Plunker The original plunker contains a text box with autocomplete functionality using hardcoded options in a list. In the new plunker, I have implem ...

Display a loading spinner by utilizing a helper function with the React context API

I'm still learning about the React Context API and I've run into an issue. I'm trying to implement a loader that starts when I make an API call and stops once the call is complete. However, when I try to dispatch actions from a helper functi ...

Are you familiar with manipulating Arrays or Objects in jQuery?

In JavaScript, we can create objects with keys as strings for similar functionality to an associate array. Check out this example here. For example: ".home-title":[ ["font-size","12px"], ["line-height","16px"], ], However, if you need a ...

Encountered an exception while trying to retrieve data with a successful status code of 200

Why is a very simple get() function entering the catch block even when the status code is 200? const { promisify } = require('util'); const { get, post, patch, del } = require('https'); //const [ getPm, postPm, patchPm, deletePm ] = [ ...

Having trouble with the npm package installation for react-circular-progressbar

I encountered an error when trying to install react-circular-progressbar in my React projects. Why is this happening? npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/em ...

Checking the content of a textfield in React Material UI based on the user input

Hello! I am seeking a solution to trigger an error message whenever the value entered in the first text field is not equal to "28.71", otherwise display a correct message. Here is my current code: class Main extends React.PureComponent { render() { ...

Ways to transmit data multiple times within a single request

I'm currently developing an app using Nodejs and express, where orders can be placed for specific products. In this application, when an order is received, it is saved in the database and a PDF receipt is generated immediately. However, since generati ...

Filter Angular by columns that change dynamically

I have a filter function that works well when I use a static column name like this: this.listOfData = this.listOfData.filter((item: DataItem) => item.name.toLowerCase().indexOf(newValue.toLowerCase()) !== -1 ); Note: item.name However, I need to sea ...

Rendering Local HTML with local styling and scripts in React Native Webview

I am having trouble loading a local HTML, CSS, and JS file in my React Native webview. The CSS is not being applied to the HTML. Here is my folder structure: https://i.sstatic.net/mqYT9.png My HTML file, along with CSS, images, and JS file are all placed ...

Looping through JSON data to dynamically generate DIV elements

Currently, I have in my possession a JSON array that contains various values. To convert this List to JSONArray, I employed the JSON-lib and some groovy classes. Along with the JSON array, I also have a JS file and a JSF for the front end. My task at hand ...

Reset hover effect upon exiting the current website

Hey there! I am currently dealing with an interesting situation regarding a link styled as a button on my website. <a href="http://externalsite" class="button" target="_blank">go to external site</a> Additionally, I have applied a hover effec ...

Conceal the div element if the screen size drops below a certain threshold

Is it possible to hide a div element when the browser width is less than or equal to 1026px using CSS, like this: @media only screen and (min-width: 1140px) {}? If not, what are some alternative solutions? Additional information: When hiding the div eleme ...

What is the quickest way to increase value in the DOM?

Is there a more efficient method for incrementing a DOM value that you know of? let progress = +document.getElementById("progress").innerHTML; progress++; document.getElementById("progress").innerHTML = progress; Perhaps something like t ...

The process of converting a string containing a list of object properties into separate objects using JavaScript

I am trying to transform the following string into actual objects. It seems that JSON.parse is not functioning as expected because all the properties are grouped together in a single string instead of being separate. This text string is retrieved from an A ...

Using Jcrop and Pixastic for Image Cropping

Currently, I am in the process of creating a website focused on image manipulation. I have been utilizing a lot of functions in Pixastic, which have proven to be quite effective. However, I have been contemplating if there is room for improvement specifica ...

Steps for setting up a nickname for individuals within the immediate scope

One snippet of HTML I utilize with ng-include involves a template that is used recursively and requires a scope/controller (apologies, as I am uncertain about the appropriate term in this scenario) named "element": <div> <span>{{element.name}} ...

Retrieving complete database in JSON format with the help of the mysql node.js driver

Currently, I am working on developing a JavaScript file to extract a JSON dump from an entire MySQL database that is running on the server side. I have successfully found and implemented the MySQL driver for node.js for executing queries. While the process ...