The Renderer
import type { RasterChartRenderer } from '@tiptap-pro/extension-diagrams'
import { Chart, registerables } from 'chart.js'
Chart.register(...registerables)
export const chartJsRenderer: RasterChartRenderer = {
id: 'chartjs',
label: 'Chart.js',
types: ['bar', 'line', 'pie', 'doughnut'],
mount(target, input) {
const canvas = document.createElement('canvas')
target.replaceChildren(canvas)
const chart = new Chart(canvas, toChartJsConfig(input))
return {
update: (next) => {
const config = toChartJsConfig(next)
chart.data = config.data
chart.options = config.options
chart.update('none')
},
destroy: () => chart.destroy(),
}
},
toImage(input) {
const canvas = document.createElement('canvas')
canvas.width = input.size.width
canvas.height = input.size.height
const chart = new Chart(canvas, { ...toChartJsConfig(input), options: { animation: false } })
return new Promise((resolve, reject) =>
canvas.toBlob((blob) => {
chart.destroy()
blob ? resolve(blob) : reject(new Error('No picture.'))
}, 'image/png'),
)
},
}toChartJsConfig turns the Chart Data and the Chart Spec into a Chart.js configuration, in the
colors of input.theme. The demo has a complete one.
- An SVG file holds the PNG, not shapes, and
exportreturnsraster: true. - Draw without animation in
toImage. Also passresponsive: falsewith a fixeddevicePixelRatio, so the PNG has exactly the size that was asked for. - A server has no canvas. So
toImageruns only in a browser, or with a canvas library of your own.