chartjs / chartjs/chartjs-plugin-datalabels

Bug: NodeJS Canvas Render Aligns Labels Wrongly

Open
#422 0 comments 4 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
920
Forks
507
PR merge metrics
No merged PRs in 30d

Description

With this example: https://codepen.io/usmortality/pen/KKjbzrj the datalabels render correctly.
![Screenshot 2024-09-05 at 6 23 50 PM](https://github.com/user-attachments/assets/7396bc31-2c08-48b0-9169-a70dc30fdb20)

And the same rendered via simple nodejs/canvas server side renderer do not:
![localhost](https://github.com/user-attachments/assets/104887b0-16b5-41ed-851c-75a12eec77e0)
```js
import express from 'express'
import path from 'path'
import { createCanvas } from 'canvas'
import { Chart, registerables } from 'chart.js'
import ChartDataLabels from 'chartjs-plugin-datalabels'

import { fileURLToPath } from 'url'

global.window = Object.assign(globalThis, {})

Chart.register(...registerables, ChartDataLabels)

const app = express()
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
app.use(
express.static(path.resolve(__dirname, '../../client/dist/'), {
index: false,
})
)

app.get('/', async (_, res) => {
const canvas = createCanvas(600, 600)
const ctx = canvas.getContext('2d')

Chart.register(ChartDataLabels)
const data = {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [
{
type: 'bar',
label: '1st Cycle',
data: [65, 59, 80, 81, 56, 55, 40],
datalabels: {
align: 'end',
anchor: 'end',
},
borderColor: ['rgb(54, 162, 235)'],
backgroundColor: ['rgba(54, 162, 235, 0.2)'],
borderWidth: 1,
},
{
type: 'bar',
label: '2nd Cycle',
data: [45, -29, 40, 51, -36, 75, -60],
borderColor: ['rgb(255, 159, 64)'],
backgroundColor: ['rgba(255, 159, 64, 0.2)'],
borderWidth: 1,
},
{
type: 'line',
label: 'Target',
data: [100, 100, 100, 100, 100, 100, 100],
datalabels: {
align: 'start',
anchor: 'start',
},
borderColor: 'rgb(75, 192, 192)',
},
],
}

const config = {
type: 'scatter',
data: data,
options: {
scales: {
y: {
beginAtZero: true,
title: {
display: true,
text: 'Percentage',
},
},
},
plugins: {
title: {
display: true,
text: 'Locality Coverage For IRS Jan-Jun, Year xxxx (Target 100%)',
},
legend: {
position: 'bottom',
},
datalabels: {
display: true,
color: 'black',
anchor: 'end',
align: 'top',
formatter: (value, context) => {
return value + '%'
},
},
},
},
}

new Chart(ctx, config)
const image = canvas.toBuffer()
res.set('Content-Type', 'image/png')
res.send(image)
})

const port = process.env.PORT ?? 5000
app.listen(port, () =>
console.log('Server is running on http://localhost:' + port)
)
```

Any ideas why?

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.