Skip to content

Commit

Permalink
Enable centered label drawing for doughnut controllers (#825)
Browse files Browse the repository at this point in the history
* Enable centered label drawing for doughnut controllers

* InnerLabel uses the label annotation

* moves code in afterUpdate hook

* adds listeners to events

* changes context type for innerlabel

* moves to a specific element for doughnut inner label

* removes specific context type for innerlabel

* fixes returned properties when there is not any doughnut controller

* removes inner label plugin and all managed by annotaiton one

* adds js doc and fix some CC issues

* improves controller retriever

* creates helpers.callout

* fixes visibility check on elements

* test cases

* improves filter on array and more tests

* types def

* add documentation

* fix lint

* add samples

* fixes animations and options

* no extension from label and background not a box but arc

* aply some reviews

* lint

* fixes test cases

* fixes color animation

* fixes font and colors options as indexable

* adds new test cases for background

* fixes types

* fixes docs and samples

* CC and color animations

* change doc about animations

* apply new features coming from other PRs after merging

* adds test cases for init animation

* apply review

* fix lineHeight on multiple font when size must be updated by fit ratio

* add hitTolerance

* apply review
  • Loading branch information
stockiNail authored Oct 10, 2024
1 parent 1702e13 commit 938ef5c
Show file tree
Hide file tree
Showing 75 changed files with 1,918 additions and 180 deletions.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ For Chart.js 2.4.0 to 2.9.x support, use [version 0.5.7 of this plugin](https://

This plugin draws lines, boxes, points, labels, polygons and ellipses on the chart area.

Annotations work with line, bar, scatter and bubble charts that use linear, logarithmic, time, or category scales. Annotations will not work on any chart that does not have two or more axes, including pie, radar, and polar area charts.
Annotations work with line, bar, scatter and bubble charts that use linear, logarithmic, time, or category scales.
Furthermore you can use a doughnut label annotation which can be used to add contents (text, image, canvas) in the middle area of the doughnut charts.

![Example Screenshot](docs/guide/banner.png)

Expand Down
13 changes: 12 additions & 1 deletion docs/.vuepress/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,8 @@ export default defineConfig({
'types/label',
'types/line',
'types/point',
'types/polygon'
'types/polygon',
'types/doughnutLabel'
]
},
'developers',
Expand Down Expand Up @@ -220,6 +221,16 @@ export default defineConfig({
'polygon/shadow'
]
},
{
title: 'Doughnut label annotations',
children: [
'doughnutLabel/basic',
'doughnutLabel/canvas',
'doughnutLabel/image',
'doughnutLabel/gauge',
'doughnutLabel/background',
]
},
{
title: 'Charts',
children: [
Expand Down
1 change: 1 addition & 0 deletions docs/diagrams/elementDoughnutLabelProps.drawio
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<mxfile host="Electron" modified="2023-01-04T15:27:51.065Z" agent="5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) draw.io/20.6.2 Chrome/106.0.5249.199 Electron/21.3.3 Safari/537.36" etag="UwpRt7ZZ2I8QNyQM25Nf" version="20.6.2" type="device"><diagram id="EVLCtf8sz0nmjKRDlPg8" name="Page-1">7ZfZjpswFIafhstUYLMkl4VZoqqVKkXVtFeVJzhg1XCocRqSp68NJonjjKaVMotGw03w7+Pt+31s4uGs6m4FacovkFPuIT/vPHzlIRT401j9aGU7KNNgOgiFYLkJOggLtqNjS6OuWU5bK1ACcMkaW1xCXdOltDQiBGzssBVwe9SGFNQRFkvCXfWO5bI0q0DJQZ9TVpTjyEE8G2oqMgablbQlyWFzJOFrD2cCQA5vVZdRruGNXIZ2Nw/U7icmaC3/pUF6t5vHP3dh1szR76+Lifz86dvE9PKH8LVZsJms3I4EBKzrnOpOfA+nm5JJumjIUtdulOdKK2XFVSlQr+6kxhGokLQ7kswkbylUVIqtCjG1yDfAzI5BoSlvDvxxbLTyiP2+ITGeF/u+D1jUiyHzH5TQ45RUL2pL0scJkbYZ9umKdZpqumKcZ8BB9B3h4bkMSpwkHyILJsZ75Qhn5MKMnggldlB2Hsq2Dk+1QmmDE7RlO3LfB+idSNYS2uG86LlyVtTqfalwUcUy1ZiYSuSPpqJiea4bpw2wWvbrilIvujqxoIZaB7VSwC96ItqpsIJamgMLhbqJ8pzVRQpSQqXE8DImBslJPvhuPkRn0iF8qmwIHQsH5t+Vkfok7gs/3h19+ISbnTg6O5eUwew5TY3cvEQ6Md2T7t3H0ccI2z6GZ26q5DlNjB0Th5m8GgvV/XbTP6/KRxzal+T+k+2lfEwcH82wb9lIAZJIBnoSk5l/obsztjMUn3F2ehlnVfHwLd/XHf0jwtd/AQ==</diagram></mxfile>
4 changes: 3 additions & 1 deletion docs/guide/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,9 @@ const options = {
| Name | Option | Value
| ---- | ---- | ----
| `numbers` | `properties` | `['x', 'y', 'x2', 'y2', 'width', 'height', 'centerX', 'centerY', 'pointX', 'pointY', 'radius']`
| `numbers` | `type` | `number`
| `numbers` | `type` | `'number'`
| `colors` | `properties` | `['backgroundColor', 'borderColor']`
| `colors` | `type` | `'color'`

## Common

Expand Down
6 changes: 5 additions & 1 deletion docs/guide/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,11 @@ This plugin needs to be registered. It does not function as inline plugin.

An annotation plugin for Chart.js >= 4.0.0

This plugin draws lines, boxes, labels, points, polygons and ellipses on the chart area. Annotations work with line, bar, scatter and bubble charts that use linear, logarithmic, time, or category scales. Annotations will not work on any chart that does not have exactly two axes, including pie, radar, and polar area charts.
This plugin draws lines, boxes, labels, points, polygons and ellipses on the chart area. Annotations work with line, bar, scatter and bubble charts that use linear, logarithmic, time, or category scales.

Furthermore you can use a doughnut label annotation which can be used to add contents (text, image, canvas) in the middle area of the doughnut charts.

Annotations will not work on any chart that does not have exactly two axes, including pie, radar, and polar area charts.

![Banner](./banner.png)

Expand Down
147 changes: 147 additions & 0 deletions docs/guide/types/doughnutLabel.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
# Doughnut Label Annotations

Doughnut label annotations are used to add contents (text, image, canvas) in the middle area of the doughnut charts.

```js chart-editor
/* <block:options:0> */
const options = {
plugins: {
annotation: {
annotations: {
dLabel: {
type: 'doughnutLabel',
content: ({chart}) => ['Total',
chart.getDatasetMeta(0).total,
'last 7 months'
],
font: [{size: 60}, {size: 50}, {size: 30}],
color: ['black', 'red', 'grey']
}
}
}
}
};
/* </block:options> */

/* <block:config:1> */
const config = {
type: 'doughnut',
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'Amount',
data: [65, 59, 80, 81, 56, 55, 40]
}]
},
options
};
/* </block:config> */

module.exports = {
config
};
```

## Configuration

### Options

The following options are available for label annotations.

| Name | Type | [Scriptable](../options.md#scriptable-options) | Default
| ---- | ---- | :----: | ----
| [`autoHide`](#general) | `boolean` | Yes | `true`
| [`autoFit`](#general) | `boolean` | Yes | `true`
| [`backgroundColor`](#styling) | [`Color`](../options.md#color) | Yes | `'transparent'`
| [`backgroundShadowColor`](#styling) | [`Color`](../options.md#color) | Yes | `'transparent'`
| [`borderColor`](#styling) | [`Color`](../options.md#color) | Yes | `'transparent'`
| [`borderDash`](#styling) | `number[]` | Yes | `[]`
| [`borderDashOffset`](#styling) | `number` | Yes | `0`
| [`borderShadowColor`](#styling) | [`Color`](../options.md#color) | Yes | `'transparent'`
| [`display`](#general) | `boolean` | Yes | `true`
| [`drawTime`](#general) | `string` | Yes | `'afterDatasetsDraw'`
| [`borderJoinStyle`](#styling) | `string` | Yes | `'miter'`
| [`borderWidth`](#styling) | `number`| Yes | `0`
| [`color`](#styling) | [`Color`\|`Color[]`](../options.md#color) | Yes | `'black'`
| [`content`](#general) | `string`\|`string[]`\|[`Image`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image)\|[`HTMLCanvasElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement) | Yes | `null`
| [`font`](#styling) | [`Font`\|`Font[]`](../options.md#font) | Yes | `{}`
| [`height`](#general) | `number`\|`string` | Yes | `undefined`
| [`hitTolerance`](#general) | `number` | Yes | `0`
| [`id`](#general) | `string` | No | `undefined`
| [`init`](../configuration.html#common) | `boolean` | [See initial animation](../configuration.html#initial-animation) | `undefined`
| [`opacity`](#styling) | `number` | Yes | `undefined`
| [`position`](#position) | `string`\|`{x: string, y: string}` | Yes | `'center'`
| [`rotation`](#general) | `number`| Yes | `0`
| [`shadowBlur`](#styling) | `number` | Yes | `0`
| [`shadowOffsetX`](#styling) | `number` | Yes | `0`
| [`shadowOffsetY`](#styling) | `number` | Yes | `0`
| [`spacing`](#general) | `number`| Yes | `1`
| [`textAlign`](#general) | `string` | Yes | `'center'`
| [`textStrokeColor`](#styling) | [`Color`](../options.md#color) | Yes | `undefined`
| [`textStrokeWidth`](#styling) | `number` | Yes | `0`
| [`width`](#general) | `number`\|`string` | Yes | `undefined`
| [`xAdjust`](#general) | `number` | Yes | `0`
| [`yAdjust`](#general) | `number` | Yes | `0`

### General

The content will be rendered in the center of the chart.

| Name | Description
| ---- | ----
| `autoFit` | If `true`, the label will be automatically fit inside the chart if its dimension is bigger than the available space.
| `autoHide` | If `true`, the label will be automatically hidden if the dataset or its data items will be all hidden.
| `content` | The content to show in the annotation.
| `display` | Whether or not this annotation is visible.
| `drawTime` | See [drawTime](../options.md#draw-time).
| `height` | Overrides the height of the image or canvas element. Could be set in pixel by a number, or in percentage of current height of image or canvas element by a string. If undefined, uses the height of the image or canvas element. It is used only when the content is an image or canvas element.
| `hitTolerance` | Amount of pixels to interact with annotations within some distance of the mouse point.
| `id` | Identifies a unique id for the annotation and it will be stored in the element context. When the annotations are defined by an object, the id is automatically set using the key used to store the annotations in the object. When the annotations are configured by an array, the id, passed by this option in the annotation, will be used.
| `rotation` | Rotation of the label in degrees.
| `spacing` | The space in pixels between the inner radius of the chart and the background of the label.
| `textAlign` | Text alignment of label content when there's more than one line. Possible options are: `'left'`, `'start'`, `'center'`, `'end'`, `'right'`.
| `width` | Overrides the width of the image or canvas element. Could be set in pixel by a number, or in percentage of current width of image or canvas element by a string. If undefined, uses the width of the image or canvas element. It is used only when the content is an image or canvas element.
| `xAdjust` | Adjustment of label relative to computed position. Negative values move the label left, positive right.
| `yAdjust` | Adjustment along y-axis (top-bottom) of label relative to computed position. Negative values move the label up, positive down.

### Styling

| Name | Description
| ---- | ----
| `backgroundColor` | Fill color.
| `backgroundShadowColor` | The color of shadow. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/shadowColor).
| `borderColor` | Stroke color.
| `borderDash` | Length and spacing of dashes. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setLineDash).
| `borderDashOffset` | Offset for border line dashes. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset).
| `borderJoinStyle` | Border line join style. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineJoin).
| `borderShadowColor` | The color of the border shadow. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/shadowColor).
| `borderWidth` | Stroke width (in pixels).
| `color` | Text color. When the label to draw has multiple lines, you can use different color for each row of the label. This is enabled configuring an array of colors. When the lines are more than the configured colors, the last configuration of this option is used for all remaining lines.
| `font` | Text font. When the label to draw has multiple lines, you can use different font for each row of the label. This is enabled configuring an array of fonts. When the lines are more than the configured fonts, the last configuration of this option is used for all remaining lines.
| `opacity` | Overrides the opacity of the image or canvas element. Could be set a number in the range 0.0 to 1.0, inclusive. If undefined, uses the opacity of the image or canvas element. It is used only when the content is an image or canvas element.
| `shadowBlur` | The amount of blur applied to shadow of the box where the label is located. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/shadowBlur).
| `shadowOffsetX` | The distance that shadow, of the box where the label is located, will be offset horizontally. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/shadowOffsetX).
| `shadowOffsetY` | The distance that shadow, of the box where the label is located, will be offset vertically. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/shadowOffsetY).
| `textStrokeColor` | The color of the stroke around the text.
| `textStrokeWidth` | Stroke width around the text.

### Position

A position can be set in 2 different values types:

1. `'start'`, `'center'`, `'end'` which are defining where the label will be located
2. a `string`, in percentage format `'number%'`, is representing the percentage on the size where the label will be located

If this value is a string (possible options are `'start'`, `'center'`, `'end'` or a string in percentage format), it is applied to vertical and horizontal position in the box.

If this value is an object, the `x` property defines the horizontal alignment in the label, with respect to the center point of the chart. Similarly, the `y` property defines the vertical alignment in the label, with respect to the center point of the chart. Possible options for both properties are `'start'`, `'center'`, `'end'`, a string in percentage format. Omitted property have value of the default, `'center'`.

#### borderRadius

If this value is a number, it is applied to all corners of the rectangle (topLeft, topRight, bottomLeft, bottomRight). If this value is an object, the `topLeft` property defines the top-left corners border radius. Similarly, the `topRight`, `bottomLeft`, and `bottomRight` properties can also be specified. Omitted corners have radius of 0.

## Element

The following diagram is showing the element properties about a `'doughnutLabel'` annotation:

![label](../../img/elementDoughnutLabelProps.png)
Binary file added docs/img/elementDoughnutLabelProps.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
68 changes: 68 additions & 0 deletions docs/samples/doughnutLabel/background.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# Filling background

```js chart-editor
// <block:setup:2>
const DATA_COUNT = 6;
const MIN = 0;
const MAX = 100;

const numberCfg = {count: DATA_COUNT, min: MIN, max: MAX, decimals: 0};

const data = {
labels: ['Apples', 'Orange', 'Lime', 'Grapes', 'Apricots', 'Blackberries'],
datasets: [{
data: Utils.numbers(numberCfg)
}]
};
// </block:setup>

// <block:annotation:1>
const annotation = {
type: 'doughnutLabel',
content: ({chart}) => [chart.getDatasetMeta(0).total,
'pieces of fruits'
],
font: [{size: 48}, {size: 20}],
color: ['indigo', 'grey'],
backgroundColor: 'rgba(0, 0, 0, 0.1)',
borderColor: 'black',
borderWidth: 2,
borderDash: [7, 7],
spacing: 2
};
// </block:annotation>

/* <block:config:0> */
const config = {
type: 'doughnut',
data,
options: {
aspectRatio: 2,
plugins: {
annotation: {
annotations: {
annotation
}
}
}
}
};
/* </block:config> */

const actions = [
{
name: 'Randomize',
handler: function(chart) {
chart.data.datasets.forEach(function(dataset, i) {
dataset.data = dataset.data.map(() => Utils.rand(MIN, MAX).toFixed(0));
});
chart.update();
}
}
];

module.exports = {
actions: actions,
config: config,
};
```
71 changes: 71 additions & 0 deletions docs/samples/doughnutLabel/basic.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# Basic

```js chart-editor
// <block:setup:3>
const DATA_COUNT = 12;
const MIN = 0;
const MAX = 100;

const numberCfg = {count: DATA_COUNT, min: MIN, max: MAX, decimals: 0};

const data = {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
datasets: [{
data: Utils.numbers(numberCfg)
}]
};
// </block:setup>

// <block:annotation:1>
const annotation = {
type: 'doughnutLabel',
content: ({chart}) => ['Average',
average(chart).toFixed(2),
'on last ' + chart.data.labels.length + ' months'
],
font: [{size: 60}, {size: 50}, {size: 30}],
color: ['black', 'red', 'grey']
};
// </block:annotation>

/* <block:config:0> */
const config = {
type: 'doughnut',
data,
options: {
aspectRatio: 2,
plugins: {
annotation: {
annotations: {
annotation
}
}
}
}
};
/* </block:config> */

// <block:utils:2>
function average(chart) {
const values = chart.data.datasets[0].data;
return values.reduce((a, b) => a + b, 0) / values.length;
}
// </block:utils>

const actions = [
{
name: 'Randomize',
handler: function(chart) {
chart.data.datasets.forEach(function(dataset, i) {
dataset.data = dataset.data.map(() => Utils.rand(MIN, MAX));
});
chart.update();
}
}
];

module.exports = {
actions: actions,
config: config,
};
```
Loading

0 comments on commit 938ef5c

Please sign in to comment.