Giter Site home page Giter Site logo

typpo / quickchart-js Goto Github PK

View Code? Open in Web Editor NEW
52.0 4.0 9.0 611 KB

Javascript client for quickchart.io

Home Page: https://quickchart.io

License: MIT License

JavaScript 1.22% TypeScript 98.78%
js-charts chart-api chartjs-to-image chartjs chartjs-node

quickchart-js's Introduction

QuickChart for Javascript

npm npm Build Status

This is a Javascript client for quickchart.io, a web service for generating static charts. View the main QuickChart repository here.

Installation

If you are using npm:

npm install quickchart-js

Usage

This library provides a QuickChart object. Import it, instantiate it, and set your Chart.js config:

const QuickChart = require('quickchart-js');

const myChart = new QuickChart();
myChart.setConfig({
  type: 'bar',
  data: { labels: ['Hello world', 'Foo bar'], datasets: [{ label: 'Foo', data: [1, 2] }] },
});

Use getUrl() on your quickchart object to get the encoded URL that renders your chart:

console.log(myChart.getUrl());
// Prints:  https://quickchart.io/chart?c=%7Btype%3A%27bar%27%2Cdata%3A%7Blabels%3A%5B%27Hello+world%27%2C%27Foo+bar%27%5D%2Cdatasets%3A%5B%7Blabel%3A%27Foo%27%2Cdata%3A%5B1%2C2%5D%7D%5D%7D%7D&w=500&h=300&bkg=transparent&f=png

If you have a large or complicated chart, use getShortUrl() on your quickchart object to get a fixed-length URL using the quickchart.io web service:

const url = await myChart.getShortUrl();
console.log(url);
// Prints: https://quickchart.io/chart/render/f-a1d3e804-dfea-442c-88b0-9801b9808401

Or write it to disk:

myChart.toFile('/tmp/mychart.png');

The URLs produce this chart image:

Creating a QuickChart object

If you have an account ID and API key, authenticate using the QuickChart constructor:

const qc = new QuickChart(apiKey, accountId);

To use the free (community) version, leave it blank:

const qc = new QuickChart();

Customizing your chart

setConfig(chart: Object | string)

Use this config to customize the Chart.js config object that defines your chart. You must set this before generating a URL!

setWidth(width: int)

Sets the width of the chart in pixels. Defaults to 500.

setHeight(height: int)

Sets the height of the chart in pixels. Defaults to 300.

setFormat(format: string)

Sets the format of the chart. Defaults to png. svg is also valid.

setBackgroundColor(color: string)

Sets the background color of the chart. Any valid HTML color works. Defaults to #ffffff (white). Also takes rgb, rgba, and hsl values.

setDevicePixelRatio(ratio: float)

Sets the device pixel ratio of the chart. This will multiply the number of pixels by the value. This is usually used for retina displays. Defaults to 1.0.

setVersion(version: string)

Sets the Chart.js version to use (e.g. 2.9.4 or 3.4.0). Valid options are shown in the documentation.

setHost(host: string)

Sets the host of generated URLs. quickchart.io by default.

setScheme(scheme: string)

Sets the scheme of generated URLs. https by default.

Getting outputs

There are two ways to get a URL for your chart object.

getUrl(): string

Returns a URL that will display the chart image when loaded.

getShortUrl(): Promise

Uses the quickchart.io web service to create a fixed-length chart URL that displays the chart image. The Promise resolves with a URL such as https://quickchart.io/chart/render/f-a1d3e804-dfea-442c-88b0-9801b9808401.

Note that short URLs expire after a few days for users of the free service. You can subscribe to keep them around longer.

getSignedUrl(): string

Returns a URL that displays the chart image. It is signed with your user account to bypass rate limitations.

toBinary(): Promise

Creates a binary buffer that contains your chart image.

toDataUrl(): Promise

Returns a base 64 data URL beginning with data:image/png;base64.

toFile(pathOrDescriptor: PathLike | FileHandle): Promise

Given a filepath string or a writable file handle, creates a file containing your chart image.

More examples

Check out the examples/ directory to see other usage. Here's a simple test that uses some of the custom parameters:

const qc = new QuickChart();

qc.setConfig({
  type: 'bar',
  data: { labels: ['Hello world', 'Foo bar'], datasets: [{ label: 'Foo', data: [1, 2] }] },
});
qc.setWidth(500).setHeight(300).setBackgroundColor('transparent');

console.log(qc.getUrl());
// https://quickchart.io/chart?c=%7Btype%3A%27bar%27%2Cdata%3A%7Blabels%3A%5B%27Hello+world%27%2C%27Foo+bar%27%5D%2Cdatasets%3A%5B%7Blabel%3A%27Foo%27%2Cdata%3A%5B1%2C2%5D%7D%5D%7D%7D&w=500&h=300&bkg=transparent&f=png

Here's a more complicated chart that includes some Javascript:

qc.setConfig({
  type: 'bar',
  data: {
    labels: ['January', 'February', 'March', 'April', 'May'],
    datasets: [
      {
        label: 'Dogs',
        data: [50, 60, 70, 180, 190],
      },
    ],
  },
  options: {
    scales: {
      yAxes: [
        {
          ticks: {
            callback: function (value) {
              return '$' + value;
            },
          },
        },
      ],
    },
  },
});
qc.setWidth(500).setHeight(300).setBackgroundColor('#0febc2');

console.log(qc.getUrl());
// https://quickchart.io/chart?c=%7Btype%3A%27bar%27%2Cdata%3A%7Blabels%3A%5B%27January%27%2C%27February%27%2C%27March%27%2C%27April%27%2C%27May%27%5D%2Cdatasets%3A%5B%7Blabel%3A%27Dogs%27%2Cdata%3A%5B50%2C60%2C70%2C180%2C190%5D%7D%5D%7D%2Coptions%3A%7Bscales%3A%7ByAxes%3A%5B%7Bticks%3A%7Bcallback%3Afunction+%28value%29+%7B%0A++return+%27%24%27+%2B+value%3B%0A%7D%7D%7D%5D%7D%7D%7D&w=500&h=300&bkg=%230febc2&f=png

As we customize these charts, the URLs are getting a little long for my liking. There's a getShortUrl function that uses the QuickChart.io web service to generate a short(er), fixed-length URL:

// Fill the chart with data from 0 to 100
const data = [...Array(100).keys()];
qc.setConfig({
  type: 'bar',
  data: { labels: ['Hello world', 'Foo bar'], datasets: [{ label: 'Foo', data }] },
});

async function printShortUrl() {
  const url = await qc.getShortUrl();
  console.log(url);
}
printShortUrl();
// https://quickchart.io/chart/render/f-a1d3e804-dfea-442c-88b0-9801b9808401

Using built-in QuickChart functions

QuickChart has builtin functions: getImageFill, getGradientFill, getGradientFillHelper, and pattern.draw. These functions can be accessed via the QuickChart class. For example:

const qc = new QuickChart();
qc.setConfig({
  type: 'bar',
  data: {
    labels: ['Hello world', 'Foo bar'],
    datasets: [
      {
        label: 'Foo',
        data: [1, 2],
        backgroundColor: QuickChart.getGradientFillHelper('horizontal', ['red', 'green']),
      },
    ],
  },
});

Building the library

To build this library locally, run:

yarn build

To run tests:

yarn test

If you're editing the library and running examples, you may want to continuously build the library in the background:

yarn build:watch

# ...

node examples/simple_example.js

quickchart-js's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

quickchart-js's Issues

API Key Implementation

Hi, really enjoying the package.
I noticed that the api key isn't used in the get/post url to quickchart.io so there's no way to use your package with a paid license.

I see where the url params for the key need to go but wanted to check in and see why this hasn't been implemented.

Appreciate it

getImageFill

How to user "getImageFill" in dataset with JS api, I it always escape it in url so it not work

thanks

How to set a custom domain?

If I run a private QuickChart instance, how do I set this client to call that domain instead of quickchart.io

Awaited short-URL hidden by Discord

I don't know why, but images with dozens of data points do not display in Discord. However, if I log those (properly awaited) short URLs to a file then seconds later manually paste that URL into Discord, then chart images do show. Should I force my app to download charts to verify whether short URLs are invalid?

I don't have a SSCCE, just https://github.com/ddugovic/lishogi-discord (which empowers players to graph their 60-day rating history with the !profile command).

Fix Types for typescript annotations.

When using the package with typescrit there is an error

Could not find a declaration file for module 'quickchart-js'. '.../node_modules/quickchart-js/build/quickchart.mjs' implicitly has an 'any' type.

  There are types at '.../node_modules/quickchart-js/build/typescript/index.d.ts', but this result could not be resolved when respecting package.json "exports". The 'quickchart-js' library may need to update its package.json or typings.

I imagine is because the types in exports is not as relative path:

it should be:

"types": "./build/typescript/index.d.ts"

How to use quickchart-js with graphviz?

All examples for quickchart-js use type: 'bar' with a JSON representation of the data. What's the syntax for creating a QuickChart object with type: 'graphviz'?

Updating the npm package with the latest security fix

Hey,

I just wanted to know if there will there be an update to the npm package with the latest security fix involving the upgrade to a newer version of axios?

I have been using the quickchart-js npm package. Is there an alternative that can be used on my repository if there is no plan to update the npm package?

Limited to three points only

Hello, i'm trying to make a chart but sadly only the first 3 data are being used and the other's data are getting ignored, i end up having only 3 points on my chart.. Here's my code :
const myChart = new QuickChart(); myChart.setConfig({ type: 'line', data: { labels: ['Last ranked games by tekkyu ','Rank : '+graph.data[graph.data.length - 1].currenttierpatched , 'elo: '+stats.data.elo], datasets: [{ label: 'RR change', data: [11,34,48,68,88,94] }] }, }); myChart.setWidth(500).setHeight(300).setBackgroundColor('transparent'); let chart=(myChart.getUrl());

and the quickchart.io link generated : Link

I don't see any option with a limit of data numbers being used in the documentation so i'm very confused if anyone could help me out.

thanks

Can't set background to transparent.

QuickChart always exports with a white background no matter what.

chart.setConfig({
                      type: 'line',
                      data: {
                        datasets: [{
                          data: duelsArrayMMRNew,
                          fill: false,
                          borderColor: QuickChart.getGradientFillHelper('vertical', ['#eb3639', '#a336eb', '#36a2eb']),
                          borderWidth: 3,
                          pointRadius: 1,
                        }]
                      },
                      options: {
                        legend: {
                          display: false
                        },
                        scales: {
                        xAxes: [{
                          display: false,
                          gridLines: {
                            display: false,
                          },
                        }],
                        yAxes: [{
                          display: false,
                          gridLines: {
                            display: false,
                          },
                        }]
                      },
                      }
                    });

This outputs this URL and saving it also shows white background.

import blows up in CRA/Webpack app

Standard import doesn't work with webpack in a CRA app.

import QuickChart from 'quickchart-js'

Results in an error in the browser:

Uncaught TypeError: quickchart_js__WEBPACK_IMPORTED_MODULE_2___default(...) is not a constructor

This appears to be due to webpack choosing the browser package.json field over main or module.

One can work around it by explicitly importing the esm build:

import QuickChart from "quickchart-js/build/quickchart.esm.js";

This is not my area of expertise. Is the browser field still needed?

Missing chart.js dependency

A type is imported form chart.js in src/index.ts but chart.js is not a dependency listed in the package.json. In projects using typescript, this results in QuickChart#setConfig()'s argument being of type any unless chart.js is added as a dependency.

This screenshot was taken without chart.js installed my my project. As you can see, the parameter has an any type.
Without chart.js installed

This one was taken after installing chart.js. Here typescript knows what type the parameter should be.
With chart.js installed

TypeError: myChart.setConfig is not a function

Trying to use chart in Apps Script and getting this error. Below is my code.

const myChart = new QuickChart();
myChart.setConfig({
    type: 'bar',
    data: { labels: ['Hello world', 'Foo bar'], datasets: [{ label: 'Foo', data: [1, 2] }] },
  })
  .setWidth(800)
  .setHeight(400)
  .setBackgroundColor('transparent');

[BUG] TypeError: quickchart_js_1.default is not a constructor

Hello guys, I use this js lib to generate a chart in a NestJS project, for example:

@Injectable()
export class QuickChartClient {
  constructor() {}

  generateLineChart(data: Data[]) {
    const quickChart = new QuickChart()
    quickChart
      .setConfig({
        type: 'line',
        data: {
          labels: data.map((it) => format(Number(it.date), 'yyyy-MM-dd')),
          datasets: [],
        },
        options: {
          title: {
            display: true,
            text: 'Chart.js Line Chart',
          },
        },
      })
      .setWidth(1280)
      .setWidth(720)
      .setBackgroundColor('transparent')
      .setVersion('4')
      .setFormat('webp')
    return quickChart.getShortUrl()
  }
}

when code run into here, the error in title happened, how can I fix it?
thanks

Feature request: TypeScript type definitions

It'd be helpful to add TypeScript type definitions. Here's my version, feel free to use if you find it helpful:

declare module 'quickchart-js' {
  import * as ChartJS from 'chart.js';

  class QuickChart {
    // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
    constructor(apiKey?: string, accountId?: string);

    public setConfig(config: ChartJS.ChartConfiguration): QuickChart;
    public setWidth(width: number): QuickChart;
    public setHeight(height: number): QuickChart;
    public setBackgroundColor(color: string): QuickChart;
    public setDevicePixelRatio(ratio: number): QuickChart;
    public setFormat(fmt: string): QuickChart;

    public getUrl(): string;
    public getShortUrl(): Promise<string>;
    public toBinary(): Promise<Buffer>;
    public toFile(
      pathOrDescriptor: string | number | Buffer | URL
    ): Promise<void>;
  }

  export default QuickChart;
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.