### Install billboard.js and React Component
Source: https://github.com/naver/billboard.js/blob/master/packages/react/README.md
Install billboard.js and the @billboard.js/react component using pnpm. This is a prerequisite for using the component.
```bash
# Install billboard.js together if you don't have it already
$ pnpm add billboard.js @billboard.js/react
```
--------------------------------
### Install Release Candidate Version
Source: https://github.com/naver/billboard.js/blob/master/README.md
To install the 'release candidate' build, which precedes the latest official release, use the pnpm add command with the '@next' tag.
```bash
$ pnpm add billboard.js@next
```
--------------------------------
### UMD/CDN Usage Example
Source: https://github.com/naver/billboard.js/blob/master/MODULE_IMPORTS.md
When using the UMD build via CDN, all resolvers are auto-invoked at load time. This means methods like chart.xgrids() work out of the box without extra setup.
```html
```
--------------------------------
### Install billboard.js Locally
Source: https://github.com/naver/billboard.js/wiki/How-to-load-as-ESM-directly-from-the-browser?
Install billboard.js using npm. This command installs the package and its dependencies into your local node_modules directory.
```sh
npm i billboard.js
```
--------------------------------
### Install Puppeteer
Source: https://github.com/naver/billboard.js/wiki/How-to-generate-chart-image-in-Node.js-environment?
Install the Puppeteer package as a development dependency.
```sh
npm i puppeteer --save-dev
```
--------------------------------
### Plugin Development Commands
Source: https://github.com/naver/billboard.js/wiki/Plugin-Interface
Lists the npm commands for facilitating plugin development: `npm run start:plugin` to start the development server and `npm run build:plugin` to build the plugin.
```bash
# Running below command will facilitate on plugin development
# start dev-server
$ npm run start:plugin
# build plugin
$ npm run build:plugin
```
--------------------------------
### Install Nightly Version via pnpm
Source: https://github.com/naver/billboard.js/blob/master/README.md
Alternatively, you can install the nightly version directly from the GitHub repository using the pnpm add command with the specified branch.
```bash
$ pnpm add git+https://github.com/naver/billboard.js.git#nightly
```
--------------------------------
### Install Dependencies with pnpm
Source: https://github.com/naver/billboard.js/blob/master/DEVELOPMENT.md
Install all necessary dependency modules for billboard.js development using pnpm. This step is crucial after cloning the repository.
```bash
# Install the dependency modules.
$ pnpm install
```
--------------------------------
### Complete HTML Structure for ESM Billboard.js
Source: https://github.com/naver/billboard.js/wiki/How-to-load-as-ESM-directly-from-the-browser?
This is a full HTML example demonstrating how to set up an import map for billboard.js and its dependencies, and then generate a chart using ESM.
```html
billboard.js
```
--------------------------------
### Install Billboard.js with pnpm
Source: https://github.com/naver/billboard.js/blob/master/README.md
The standard way to install the latest stable version of Billboard.js using pnpm is by running the 'pnpm add billboard.js' command.
```bash
$ pnpm add billboard.js
```
--------------------------------
### Build billboard.js
Source: https://github.com/naver/billboard.js/blob/master/DEVELOPMENT.md
Utilize package scripts to build billboard.js for development or production. This includes starting a development server, generating a production build, and creating JSDoc documentation.
```bash
# Run webpack-dev-server for development
$ pnpm start
# Build
$ pnpm run build
# Generate jsdoc
$ pnpm run jsdoc
```
--------------------------------
### Usage Example 2: Bar and Area Chart
Source: https://github.com/naver/billboard.js/wiki/How-to-generate-chart-image-in-Node.js-environment?
This example demonstrates generating a bar and area chart and saving it as 'chart02.png'. Ensure 'transition.duration' is set to 0 to prevent rendering issues.
```js
await screenshot({
data: {
columns: [
["data1", 300, 350, 300, 0, 0, 0],
["data2", 130, 100, 140, 200, 150, 50]
],
types: {
data1: "bar",
data2: "area"
}
},
transition: {
duration: 0
}
}, "./chart02.png");
```
--------------------------------
### Usage Example 1: Area Chart
Source: https://github.com/naver/billboard.js/wiki/How-to-generate-chart-image-in-Node.js-environment?
This example demonstrates generating an area step and area spline chart and saving it as 'chart01.png'. Ensure 'transition.duration' is set to 0 to prevent rendering issues.
```js
// index.mjs
import screenshot from "./screen.mjs";
await screenshot({
data: {
columns: [
["data1", 300, 350, 300, 0, 0, 0],
["data2", 130, 100, 140, 200, 150, 50]
],
types: {
data1: "area-step",
data2: "area-spline"
}
},
// IMPORTANT:
// Specify 'transition.duration=0' to avoid partial rendering
// caused by the transition(animation).
transition: {
duration: 0
}
}, "./chart01.png");
```
--------------------------------
### Conventional Commits Body Example
Source: https://github.com/naver/billboard.js/blob/master/CONTRIBUTING.md
An example of a commit message that includes a body, detailing the changes made. It also shows how to indicate a breaking change.
```bash
():
Update condition of tick to avoid unnecessary tick rendering
```
--------------------------------
### Clone billboard.js Repository
Source: https://github.com/naver/billboard.js/blob/master/DEVELOPMENT.md
Clone the billboard.js repository to your local machine and navigate into the project directory. Ensure you have Node.js 10.10.0 or higher installed.
```bash
# Create a folder and move.
$ mkdir billboard.js && cd billboard.js
# Clone the repository.
$ git clone https://github.com/naver/billboard.js.git
```
--------------------------------
### Install Nightly Version via package.json
Source: https://github.com/naver/billboard.js/blob/master/README.md
To use the latest build from the master branch, specify the nightly version in your package.json file. This allows you to test upcoming changes before the official release.
```json
{
...
"billboard.js": "naver/billboard.js#nightly"
}
```
--------------------------------
### App Bootstrap Module Registration
Source: https://github.com/naver/billboard.js/blob/master/MODULE_IMPORTS.md
Centralize module imports and invocations in a single setup file (e.g., src/chart-setup.js) for your application. This ensures all necessary modules are registered once, allowing route-level code to use plain bb.generate() configurations.
```javascript
// src/chart-setup.js — imported once from the app entry
import {bar, line, pie, grid, regions, category, zoom} from "billboard.js";
bar(); line(); pie();
grid(); regions(); category();
zoom();
```
```javascript
// src/main.js (or pages/_app.tsx, app/layout.tsx, etc.)
import "./chart-setup"; // side-effect import — registers once
import bb from "billboard.js";
// …mount app…
```
```javascript
// src/pages/dashboard.js
import bb from "billboard.js";
// Nothing else to import. Write config the v3 way.
bb.generate({
bindto: "#a",
data: { type: "bar", columns: [...] },
grid: { x: { lines: [...] } }
});
```
```javascript
// src/pages/report.js — a totally different route
import bb from "billboard.js";
bb.generate({
bindto: "#b",
data: { type: "pie", columns: [...] }
});
// chart.regions([...]) also works here — registered by chart-setup.js
```
--------------------------------
### Import ESM Dependencies with Import Maps (Local)
Source: https://github.com/naver/billboard.js/wiki/How-to-load-as-ESM-directly-from-the-browser?
Configure import maps to point to local modules within the `node_modules` directory. This is used when billboard.js is installed locally.
```html
```
--------------------------------
### Enabling Zoom Interaction in Billboard.js
Source: https://github.com/naver/billboard.js/blob/master/MODULE_IMPORTS.md
Import the 'zoom' module and enable it via the `zoom.enabled` option in `bb.generate`. This example also uses the 'bar' chart type.
```javascript
import bb, {bar, zoom} from "billboard.js";
bb.generate({
zoom: { enabled: zoom() },
data: { type: bar(), columns: [...] }
});
```
--------------------------------
### Integrating Multiple Optional API Modules in Billboard.js
Source: https://github.com/naver/billboard.js/blob/master/MODULE_IMPORTS.md
Import and integrate various optional API modules like grid, regions, category, exportApi, and flow. This example demonstrates their usage with `bb.generate` and direct chart method calls.
```javascript
import bb, {bar, grid, regions, category, exportApi, flow} from "billboard.js";
const chart = bb.generate({
...grid(),
...regions(),
...category(),
...exportApi(),
...flow(),
data: { type: bar(), columns: [...] },
grid: { x: { lines: [...] } },
regions: [{ start: 1, end: 2 }]
});
chart.xgrids([...]);
chart.regions([...]);
chart.category(0);
chart.export();
chart.flow({ columns: [...] });
```
--------------------------------
### Create Line and Bar Chart with nvd3
Source: https://github.com/naver/billboard.js/wiki/Comparison-table
Example of creating a line and bar chart using nvd3. It demonstrates data structure, chart model selection, margin configuration, and custom tick formatting for axes.
```javascript
nv.addGraph(function() {
var data = [{
"key": "Quantity",
"bar": true,
"color": "#ccf",
"values": [
[1136005200000, 1271000.0],
[1138683600000, 1271000.0],
[1141102800000, 1271000.0],
[1143781200000, 0],
[1146369600000, 0],
]
},
{
"key": "Price",
"color": "#333",
"values": [
[1136005200000, 71.89],
[1138683600000, 75.51],
[1141102800000, 68.49],
[1143781200000, 62.72],
[1146369600000, 70.39]
]
}
];
var chart = nv.models.linePlusBarChart()
.margin({
top: 30,
right: 60,
bottom: 50,
left: 70
})
//We can set x data accessor to use index. Reason? So the bars all appear evenly spaced.
.x(function(d, i) {
return i
})
.y(function(d, i) {
return d[1]
});
chart.xAxis.tickFormat(function(d) {
var dx = data[0].values[d] && data[0].values[d][0] || 0;
return d3.time.format('%x')(new Date(dx))
});
chart.y1Axis.tickFormat(d3.format(',f'));
chart.y2Axis.tickFormat(function(d) {
return '$' + d3.format(',f')(d)
});
chart.bars.forceY([0]);
d3.select('#chart svg')
.datum(data)
.transition()
.duration(0)
```
--------------------------------
### Conventional Commits Type Examples
Source: https://github.com/naver/billboard.js/blob/master/CONTRIBUTING.md
Examples of commit types and their usage. 'skip:' type is used for commits made after the first one, often for code review changes, and is ignored by commit hooks.
```bash
fix(Axis): Correct tick rendering
```
```bash
skip: Applied the review
```
--------------------------------
### Conventional Commits Footer Example
Source: https://github.com/naver/billboard.js/blob/master/CONTRIBUTING.md
Illustrates how to reference related GitHub issues in the commit footer using the 'Ref #ISSUE-NO' format. Also shows the 'BREAKING CHANGE:' notation.
```bash
Ref #20
```
```bash
fix(Axis): Correct tick rendering
Update condition of tick to avoid unnecessary tick rendering
Ref #20
```
```bash
feat(tooltip): Intent to ship tooltip.contents.template
- Implementation of tooltip.contents.template
- Update legend template processing with util's .tplProcess()
Ref #813
```
```bash
feat(browser): Drop support for IE 11
Drop support for IE 11.
Ref #31
BREAKING CHANGE: Internet Explorer 11 is a burden to support and at EOL.
```
--------------------------------
### Create Mixed Chart with Chart.js
Source: https://github.com/naver/billboard.js/wiki/Comparison-table
Example of creating a mixed chart (bar and line) with Chart.js. It shows how to define datasets with different types and configure chart options like axes, title, and legend.
```javascript
var mixedChart = new Chart(document.getElementById("myChart"), {
type: 'bar',
data: {
datasets: [{
label: 'Bar Dataset',
data: [10, 20, 30, 40],
backgroundColor: 'rgba(255, 99, 132, 0.2)',
}, {
label: 'Line Dataset',
data: [0, 15, 30, 50],
borderColor: 'rgba(255, 255, 0, 0.1)',
backgroundColor: 'rgba(255, 99, 132, 0.1)',
// Changes this dataset to become a line
type: 'line'
}],
labels: ['January', 'February', 'March', 'April']
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
},
title: {
display: true,
text: 'Chart.js example'
},
legend: {
display: true,
position: 'bottom'
}
}
});
```
--------------------------------
### Generate Temperature and Rainfall Chart with Highcharts
Source: https://github.com/naver/billboard.js/wiki/Comparison-table
Highcharts example for plotting temperature (spline) and rainfall (column) on a chart with dual y-axes. Demonstrates configuration for chart type, axes formatting, tooltips, and legend.
```javascript
Highcharts.chart('container', {
chart: {
zoomType: 'xy'
},
title: {
text: 'Average Monthly Temperature and Rainfall in Tokyo'
},
subtitle: {
text: 'Source: WorldClimate.com'
},
xAxis: [{
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
crosshair: true
}],
yAxis: [{ // Primary yAxis
labels: {
format: '{value}°C',
style: {
color: Highcharts.getOptions().colors[1]
}
},
title: {
text: 'Temperature',
style: {
color: Highcharts.getOptions().colors[1]
}
}
}, { // Secondary yAxis
title: {
text: 'Rainfall',
style: {
color: Highcharts.getOptions().colors[0]
}
},
labels: {
format: '{value} mm',
style: {
color: Highcharts.getOptions().colors[0]
}
},
opposite: true
}],
tooltip: {
shared: true
},
legend: {
layout: 'vertical',
align: 'left',
x: 120,
verticalAlign: 'top',
y: 100,
floating: true,
backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'
},
series: [{
name: 'Rainfall',
type: 'column',
yAxis: 1,
data: [49.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4],
tooltip: {
valueSuffix: ' mm'
}
}, {
name: 'Temperature',
type: 'spline',
data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6],
tooltip: {
valueSuffix: '°C'
}
}]
});
```
--------------------------------
### Run the script
Source: https://github.com/naver/billboard.js/wiki/How-to-generate-chart-image-in-Node.js-environment?
Execute the index.mjs script to generate the chart images.
```sh
node index.mjs
# ==> will generate 'chart01.png' and 'chart02.png'
```
--------------------------------
### Custom Plugin Implementation Outline
Source: https://github.com/naver/billboard.js/wiki/Plugin-Interface
Provides a detailed outline for a custom plugin's `index.js` file, including constructor logic, lifecycle hooks ($beforeInit, $init, $redraw, $willDestroy), and how to access options and the chart instance (`$$`). Business logic should be placed within lifecycle hooks.
```javascript
class MyPlugin extends Plugin {
constructor(options) {
// plugin's option if necessary
// calling 'super', will assign options as instance member
super(options);
// you can access options as instance member
this.options;
// NOTE:
// Do not write business logic here, write within one of
// lifecycle hook methods($beforeInit, $init, etc.).
// At this point, chart isn't instantiated yet.
}
// will be executed at 'beforeInit' lifecycle
// lifecycle hook is optional. Do not specify if isn't necessary
$beforeInit() {
// the current chart instance variable 'this.$$'
// will be assigned by default as time of the initialization
this.$$; // access current chart instance's `chart.internal`
}
// 'init' hook (required)
$init() {
// write initial code for the plugin
}
// 'redraw' hook (required)
$redraw() {
// will be triggered as time of
// "redraw"(resize, data toggle, etc.) happens
}
// 'willDestroy' hook (not mandatory, but highly recommended to implement)
// will be triggered when '.destroy()' is called
$willDestroy() {
// write code releasing the resources used in this plugin
}
}
```
--------------------------------
### Basic React Component Usage
Source: https://github.com/naver/billboard.js/blob/master/packages/react/README.md
Demonstrates how to use the BillboardJS React component. It shows how to import necessary modules, set up chart options, and access the chart instance using a ref for API calls.
```jsx
import React, {useEffect, useRef} from "react";
// import billboard.js
import bb, {line} from "billboard.js";
import "billboard.js/dist/billboard.css"; // default css
// import react wrapper
import BillboardJS, {IChart} from "@billboard.js/react";
// const BillboardJS = require("@billboard.js/react"); // for CJS
function App() {
// to get the instance, create ref and pass it to the component
const chartComponent = useRef(null);
const options = {
data: {
columns: [
["data1", 300, 350, 300]
],
type: line()
}
};
useEffect(() => {
// get the instance from ref
const chart = chartComponent.current?.instance;
// call APIs
if (chart) {
chart.load( ... );
}
}, []);
return ;
}
```
--------------------------------
### Basic Plugin Integration in Billboard.js
Source: https://github.com/naver/billboard.js/wiki/Plugin-Interface
Demonstrates how to include plugins when generating a chart and how to access the instantiated plugins via the `chart.plugins` property. Plugin options are isolated from the main chart options.
```javascript
const chart = bb.generate({
plugins: [
new PluginA({ options }),
new PluginB( ... ),
...
]
});
// Accesing plugin property
// [PluginA Instance, PluginB Instance, ...]
chart.plugins;
```
--------------------------------
### Importing Chart Types in Billboard.js
Source: https://github.com/naver/billboard.js/blob/master/MODULE_IMPORTS.md
Import specific chart types and pass their return values to `data.type` or `data.types`. This example shows how to use the 'bar' and 'line' types.
```javascript
import bb, {bar, line} from "billboard.js";
bb.generate({
data: {
type: bar(), // single type
types: { data2: line() },
columns: [["data1", 30, 200], ["data2", 100, 50]]
}
});
```
--------------------------------
### Load Billboard.js and Themes
Source: https://github.com/naver/billboard.js/blob/master/demo/index.html
Initializes billboard.js by loading necessary JS and CSS files, including theme selection. Handles browser compatibility for Edge.
```javascript
var path = ["../dist/", "../../gh-pages/release/latest/dist/"]; // var path = ["https://naver.github.io/billboard.js/release/3.9.0/dist/"]; !function() { var cssFileName = localStorage.cssThemeName; cssFileName = cssFileName ? "theme/" + cssFileName : "billboard"; /Edge/.test(navigator.userAgent) && /github.io/.test(location.hostname) && path.reverse(); fallback.load({ billboard_js: path.map(function(p) { return p + "billboard.js" }), billboard_css: path.map(function(p) { return p + cssFileName + ".css" }), // plugins_stanford: path.map(function(p) { // return p + "plugin/billboardjs-plugin-stanford.js" // }) }); $(function() { var $select = $("#theme select"); $select.on("change", function() { var value = this[this.options.selectedIndex].value; if (value !== localStorage.cssThemeName) { localStorage.cssThemeName = value; location.reload(); } }); // add 'dark' classname to body when dark theme is selected document.body.classList[cssFileName.indexOf("dark") > -1 ? "add" : "remove"]("dark"); $select.children().toArray() .forEach(function(v) { v.selected = cssFileName.indexOf(v.value) > -1; }); }); }();
```
--------------------------------
### Common billboard.js Commands
Source: https://github.com/naver/billboard.js/blob/master/AGENTS.md
Essential commands for developing, building, testing, and formatting the billboard.js project using pnpm.
```bash
pnpm start
```
```bash
pnpm run build
```
```bash
pnpm run build:dev
```
```bash
pnpm run lint
```
```bash
pnpm run format
```
```bash
pnpm test
```
```bash
pnpm exec vitest test/shape/bar-spec.ts
```
```bash
pnpm exec vitest -t "pattern"
```
```bash
pnpm run coverage
```
--------------------------------
### Generate Chart with Canvas Rendering Mode
Source: https://github.com/naver/billboard.js/blob/master/CHANGELOG-v4.md
Example of generating a bar chart using the canvas rendering mode. It configures theme selectors for axis ticks, grid lines, and bars.
```javascript
bb.generate({
render: {
mode: canvas()
},
canvas: {
theme: {
selectors: {
".bb-axis .tick text": {fill: "#555", font: "12px sans-serif"},
".bb-grid line": {stroke: "#ddd", "stroke-width": 1},
".bb-bar": {stroke: "#fff", "stroke-width": 1}
}
}
},
data: {
columns: [
["data1", 30, 200, 100, 400]
],
type: bar()
}
});
```
--------------------------------
### Import billboard.js packaged build
Source: https://github.com/naver/billboard.js/wiki/How-to-bundle-for-legacy-browsers?
Use the pre-packaged build of billboard.js when direct transpilation of d3 modules is not desired. This build already includes necessary d3 modules, simplifying integration for legacy environments.
```javascript
import {bb} from "billboard.js/dist/billboard.pkgd";
bb.generate(...);
```
--------------------------------
### Initial Data for Category Axis
Source: https://github.com/naver/billboard.js/wiki/How-behaves-for-dynamic-loading?
Sets up initial data for a chart with a category axis type, specifying the 'x' column and its categorical values.
```javascript
// initial
data: {
x: "x",
columns: [
["x", "a1", "a2", "a3", "a4", "a5"],
["a", 12, 15, 6, 23, 13]
]
},
axis: {
x: {
type: "category"
}
}
```
--------------------------------
### Load Data: Replace 'x' Axis with Existing Dataset (Indexed/Timeseries)
Source: https://github.com/naver/billboard.js/wiki/How-behaves-for-dynamic-loading?
Illustrates loading new columns including an existing dataset ('a' in this case). This scenario behaves like 'Case 1', replacing the previous 'x' axis values.
```javascript
chart.load({
columns: [
["x",0, 5, 7, 12, 20],
["a", 7, 7, 7, 7, 7],
["b", 12, 9, 31, 26, 17]
]
});
```
--------------------------------
### Specify Relative Padding with 'Fit' Mode in Billboard.js
Source: https://github.com/naver/billboard.js/wiki/Understanding-padding
In 'fit' mode, padding values are applied relatively, starting from the 'fit' mode's initial state. Specifying all directions as 0 maintains the initial 'fit' state. Values increase padding from the visible element's position.
```javascript
padding: {
mode: "fit",
top: 20,
bottom: 20,
left: 20,
right: 20
}
```
--------------------------------
### Load Billboard.js Plugins
Source: https://github.com/naver/billboard.js/blob/master/demo/index.html
Loads various billboard.js plugins using fallback.load after the initial script is ready. Includes plugins for Stanford, text overlap, bubble comparison, table view, and sparkline.
```javascript
fallback.ready(function(e) { // load plugin fallback.load({ plugins_stanford: path.map(function(p) { return p + "plugin/billboardjs-plugin-stanford.js" }), plugins_textoverlap: path.map(function(p) { return p + "plugin/billboardjs-plugin-textoverlap.js" }), plugins_bubblecompare: path.map(function(p) { return p + "plugin/billboardjs-plugin-bubblecompare.js" }), plugins_tableview: path.map(function(p) { return p + "plugin/billboardjs-plugin-tableview.js" }), plugins_sparkline: path.map(function(p) { return p + "plugin/billboardjs-plugin-sparkline.js" }) }); fallback.ready(function() { billboardDemo.init(); }); });
```
--------------------------------
### Initialize Chart on Load
Source: https://github.com/naver/billboard.js/blob/master/benchmark/canvas-demo.html
Calls the render function to display the initial chart when the page loads.
```javascript
render();
```
--------------------------------
### Load Billboard.js with D3.js via Script Tags
Source: https://github.com/naver/billboard.js/blob/master/README.md
Include D3.js and Billboard.js separately using script tags. Ensure the CSS is also linked.
```html
```
--------------------------------
### Run Tests with Vitest
Source: https://github.com/naver/billboard.js/blob/master/DEVELOPMENT.md
Perform comprehensive tests using Vitest in browser mode before pushing changes. This command ensures the stability and correctness of your development work.
```bash
$ pnpm test
```
--------------------------------
### Create Screenshot Module
Source: https://github.com/naver/billboard.js/wiki/How-to-generate-chart-image-in-Node.js-environment?
This module uses Puppeteer to launch a browser, load Billboard.js assets, generate a chart based on provided options, and take a screenshot.
```js
// screen.mjs
import puppeteer from "puppeteer";
/**
* Generate chart image screenshot
* @param {object} options billboard.js generation option object
* @param {string} path screenshot image full path with file name
*/
export default async function screenshot(options = {}, path = "chart.png") {
const browser = await puppeteer.launch();
const page = await browser.newPage();
// load billboard.js assets from CDN
await page.addStyleTag({ url: "https://cdn.jsdelivr.net/npm/billboard.js/dist/theme/datalab.min.css" });
await page.addScriptTag({ url: "https://cdn.jsdelivr.net/npm/billboard.js/dist/billboard.pkgd.min.js" });
await page.evaluate(options => {
bb.generate(options);
}, options);
const content = await page.$(".bb");
// https://pptr.dev/#?product=Puppeteer&show=api-pagescreenshotoptions
await content.screenshot({
path,
omitBackground: true
});
await page.close();
await browser.close();
}
```
--------------------------------
### Import UMD Build in v2 (for v1.x compatibility)
Source: https://github.com/naver/billboard.js/wiki/Migration-Guide-to-v2
To maintain v1.x behavior with ESM imports in v2, you can import the UMD build. Note that this will not provide the tree-shaking benefits.
```javascript
// v2 - import UMD build
import bb from "billboard.js/dist/billboard.js";
bb.generate({
data: {
...
type: "bar"
}
});
```
--------------------------------
### Britecharts Animated Line Chart
Source: https://github.com/naver/billboard.js/wiki/Comparison-table
Configures and renders an animated line chart using Britecharts. Includes settings for aspect ratio, grid, tooltip, and event handling.
```js
var lineChart = new line();
var container = d3.select('.js-container');
lineChart
.isAnimated(true)
.aspectRatio(0.5)
.grid('horizontal')
.tooltipThreshold(600)
.width(600)
.dateLabel('fullDate')
.on('customMouseOver', chartTooltip.show)
.on('customMouseMove', chartTooltip.update)
.on('customMouseOut', chartTooltip.hide);
container.datum({
dataByTopic: [
{
topicName: 'San Francisco',
topic: 123,
dates: [
{
date: '2017-01-16T16:00:00-08:00',
value: 1
},
{
date: '2017-01-16T17:00:00-08:00',
value: 2
}
]
},
{
topicName: 'Other',
topic: 345,
dates: [
{...},
{...}
]
}
]
}).call(lineChart);
```
--------------------------------
### ESM Imports: v1 Basic Import
Source: https://github.com/naver/billboard.js/wiki/Migration-Guide-to-v2
This is the standard way to import Billboard.js using UMD build in v1.x.
```javascript
// v1
import bb from "billboard.js";
bb.generate({
...,
data: {
type: "line",
// or specifying type for each data
types: {
data1: "bar",
data1: "area-spline"
}
selection: {
enabled: true
}
},
subchart: {
show: true
},
zoom: {
enabled: true
}
});
```
--------------------------------
### Enable Chart Type and Grid with Inline Spread
Source: https://github.com/naver/billboard.js/blob/master/MODULE_IMPORTS.md
Use inline spread syntax with module resolvers like bar() and grid() directly within bb.generate() to enable features and apply default configurations for a single chart.
```javascript
import bb, {bar, grid} from "billboard.js";
bb.generate({
...bar(), // enable "bar" chart type
...grid(), // enable chart.xgrids() / chart.ygrids() + grid renderer
data: { columns: [...] }
});
```
--------------------------------
### Import ESM Dependencies with Import Maps (Online)
Source: https://github.com/naver/billboard.js/wiki/How-to-load-as-ESM-directly-from-the-browser?
Use this method to load billboard.js and its dependencies from CDNs directly in the browser. It requires specifying the module mappings in a script tag with type 'importmap'.
```html
```
--------------------------------
### Basic Plugin Structure
Source: https://github.com/naver/billboard.js/wiki/Plugin-Interface
This snippet shows the basic structure for creating an independent Billboard.js plugin. Ensure you import the base Plugin class.
```javascript
import Plugin from "billboard.js/src/Plugin/Plugin";
export default class MyPlugin extends Plugin {
...
}
```
--------------------------------
### Billboard.js with Canvas Rendering Mode
Source: https://github.com/naver/billboard.js/blob/master/README.md
Import billboard.js from the '/canvas' entry point and configure it to use canvas rendering by setting `render.mode` to `canvas()`.
```javascript
import bb, {bar, canvas} from "billboard.js/canvas";
bb.generate({
render: {
mode: canvas()
},
data: {
columns: [
["data1", 30, 200, 100, 400]
],
type: bar()
}
});
```
--------------------------------
### Linting and Testing Commands
Source: https://github.com/naver/billboard.js/blob/master/CONTRIBUTING.md
Commands to run for code linting and testing. Ensure all tests pass on the latest Chrome version before submitting a pull request.
```bash
pnpm run lint
```
```bash
pnpm test
```
--------------------------------
### Load Data: Add New Dataset (No 'x')
Source: https://github.com/naver/billboard.js/wiki/How-behaves-for-dynamic-loading?
Shows loading a new dataset ('b') when no 'x' value is specified. This adds the new dataset without altering the existing data or 'x' ticks.
```javascript
// will add dataset 'b' to be displayed, w/o changes
chart.load({
columns: [
["b", 12, 9]
]
});
```
--------------------------------
### Register Modules Once for Multiple Charts
Source: https://github.com/naver/billboard.js/blob/master/MODULE_IMPORTS.md
For applications generating multiple charts, invoke module resolvers like bar(), line(), grid(), and regions() once at the module's top. Subsequent bb.generate() calls can then use plain configuration objects.
```javascript
import bb, {bar, line, grid, regions} from "billboard.js";
// Run once per app — prototype registration is global and idempotent.
bar();
line();
grid();
regions();
// From here on, write config the familiar way.
const chartA = bb.generate({
bindto: "#chartA",
data: { type: "bar", columns: [["data1", 30, 200, 100, 400]] },
grid: { x: { lines: [{ value: 2, text: "Mark" }] } }
});
const chartB = bb.generate({
bindto: "#chartB",
data: {
types: { revenue: "bar", trend: "line" },
columns: [["revenue", 300, 350, 300], ["trend", 130, 100, 140]]
},
regions: [{ axis: "x", start: 1, end: 2, class: "highlight" }]
});
```
--------------------------------
### Lint Code with ESLint
Source: https://github.com/naver/billboard.js/blob/master/DEVELOPMENT.md
Ensure code style and quality consistency by running the ESLint linter. This command checks your code against predefined rules.
```bash
$ pnpm run lint
```
--------------------------------
### Load Data: Shorter Length than Original (No 'x')
Source: https://github.com/naver/billboard.js/wiki/How-behaves-for-dynamic-loading?
Demonstrates loading data with fewer points than the original dataset when no 'x' value is specified. The existing 'x' ticks will be scaled to match the new data length.
```javascript
// previous 'x' will be scaled according the given data length
chart.load({
columns: [
["a", 12, 9]
]
});
```
--------------------------------
### Import Billboard.js as ESM
Source: https://github.com/naver/billboard.js/blob/master/README.md
Import billboard.js and its modules using named or default imports. CSS can also be imported if your environment supports it.
```javascript
// 1) import billboard.js
// as named import with desired shapes and interaction modules
// https://github.com/naver/billboard.js/wiki/CHANGELOG-v2#modularization-by-its-functionality
import {bb, area, bar, zoom} from "billboard.js";
// or as importing default
import bb, {area, bar, zoom} from "billboard.js";
// 2) import css if your dev-env supports. If don't, include them via
import "billboard.js/dist/billboard.css";
// or theme style. Find more themes from 'theme' folder
import "billboard.js/dist/theme/insight.css"
```
--------------------------------
### Google Analytics Integration
Source: https://github.com/naver/billboard.js/blob/master/demo/index.html
Initializes Google Analytics tracking for the page. This snippet should be included for analytics purposes.
```javascript
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-100680234-1', 'auto'); ga('send', 'pageview');
```
--------------------------------
### Export Chart as PNG
Source: https://github.com/naver/billboard.js/blob/master/benchmark/canvas-demo.html
Exports the current chart as a PNG image and triggers a download. This function requires a chart instance to be available.
```javascript
document.getElementById("export").addEventListener("click", function() {
if (!chart) {
return;
}
var link = document.createElement("a");
link.download = "billboard-canvas.png";
link.href = chart.export();
link.click();
});
```
--------------------------------
### Handle Page Visibility Changes for Realtime Charts
Source: https://github.com/naver/billboard.js/wiki/How-to-implement-realtime-chart?
Implement logic to manage chart updates based on page visibility. When the page is not visible, stop rendering new data to conserve resources and prevent useless updates. Resume when the page becomes visible again, with a slight delay to ensure transitions complete.
```javascript
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "visible") {
// wrapped setTimeout here, because when you leave current visible tab,
// there's possibility of remain transition.
// In this case, when tab is visible the remained transition will be done first.
// So to not being some collision here, give some spare time to make transition be done.
setTimeout(() => {
// start flow again here
...
}, 1500)
} else {
// stop flow
}
});
```
--------------------------------
### Load Data: Replace 'x' Axis (Indexed/Timeseries)
Source: https://github.com/naver/billboard.js/wiki/How-behaves-for-dynamic-loading?
Demonstrates loading new columns that will replace the existing 'x' axis values for indexed or timeseries charts. This is used when the new 'x' data should dictate the axis.
```javascript
// the previous `x` will be replaced
chart.load({
columns: [
["x",0, 5, 7, 12, 20],
["a", 12, 9, 31, 26, 17]
]
});
```