Chart.js

Aus Wikizone
(Unterschied) ← Nächstältere Version | Aktuelle Version (Unterschied) | Nächstjüngere Version → (Unterschied)
Wechseln zu: Navigation, Suche

Chart.js ist eine Library zum Erstellen von Diagrammen. Die Diagramme werden über WegGl gerendert.

Man kann sehr effektiv Diagramme erstellen und die Ausgabe recht umfangreich anpassen.

Chart.js - Snippets[Bearbeiten]

Chart.js - Snippets

Chart.js - SVG Export[Bearbeiten]

Plugin: http://gliffy.github.io/canvas2svg/

Beispielskript:

/*
PNG AND SVG EXPORT (for Illustrator)
Jeff Thompson | 2021 | jeffreythompson.org

Online charts are great, but what if you want to share
them on social media, use them in print projects, etc?
With a little tweaking, we can export and download
any chart we make as a PNG and SVG!

SVGs are vector graphics, meaning we can also open
them in Illustrator and access all the shapes! This is
great if you want to create a base chart in code, then
style it in Illustrator to make it super cool.

Note! Your SVG may look cut off when viewing in
the web browser. Fear not: if you open it in Illustrator
you'll see everything there :)

DATA SOURCE
+ https://en.wikipedia.org/wiki/World_population

MORE INFO
+ Uses canvas2svg.js
  http://gliffy.github.io/canvas2svg

CHALLENGES
1. Try opening the SVG in Illustrator: can you ungroup
   everything and change colors and text?

*/

// set the output dimensions (helpful
// especially for PNG)
let width =  900;
let height = 600;

// (scroll down for more details...)
let data = [ 585,  660,  710,  978,  1650, 6127, 8549, 10152, 10875 ];
let labels = [ 1500, 1600, 1700, 1800, 1900, 2000, 2030, 2060, 2100 ];
let title = 'World Population (in millions)';

let options = {
  type: 'bar',
  data: {
    labels: labels,
    datasets: [{
      backgroundColor: 'rgb(255,150,0)',
      barPercentage:   1.0,
      data:            data,
      label:           'Population (in millions)'
    }]
  },
  options: {  
    title: {
      display: true,
      text: title
    },
    legend: {
      display: false
    },
    
    // these need to be set to false
    // for export!
    animation:  false,
    responsive: false
  }
}

// set the chart's size based on the
// values we set at the top
let context =    document.getElementById('canvas');
context.width =  width;
context.height = height;

// create the chart
let chart = new Chart(document.getElementById('canvas'), options);

// and generate the PNG and SVG links!
// (the code that does this is in the 'libs'
// folder > export.js)

// arguments: filename, link text, chart we created
createPngLink('chart.png', 'Export PNG, ', chart);

// arguments: filename, link text, the chart, and its settings
createSvgLink('chart.svg', 'SVG', chart, options);

export.js

function createPngLink(filename, linkText, chart) {
  if (chart.options.animation !== false) {
    console.warn('Cannot create PNG: "animation" is not set to false (see the options section)');
    return;
  }
  if (chart.options.responsive !== false) {
    console.warn('Cannot create PNG: "responsive" is not set to false (see the options section)');
    return;
  }

  // create the download link
  let link = document.createElement('a');
  link.href = chart.toBase64Image();
  link.download = filename;
  link.text = linkText;
  
  // and add it to the page
  document.getElementById('wrapper').appendChild(link);
}


function createSvgLink(filename, linkText, chart, chartSettings) {
  if (chart.options.animation !== false) {
    console.warn('Cannot create SVG: "animation" is not set to false (see the options section)');
    return;
  }
  if (chart.options.responsive !== false) {
    console.warn('Cannot create SVG: "responsive" is not set to false (see the options section)');
    return;
  }

  tweakLib();

  // get the dimensions of our original chart
  let chartCanvas = document.getElementById('canvas');
  let width =  chartCanvas.offsetWidth;
  let height = chartCanvas.offsetHeight;

  // create an svg version of the chart
  let svgContext = C2S(width, height);
  let svgChart = new Chart(svgContext, chartSettings);

  // create download link
  let link = document.createElement('a');
  link.href = 'data:image/svg+xml;utf8,' + encodeURIComponent(svgContext.getSerializedSvg());
  link.download = filename;
  link.text = linkText;

  // add link to the page
  document.getElementById('wrapper').appendChild(link);
}


// some tweaks to the canvas2svg library are required for this to work
// via: https://stackoverflow.com/questions/62249315/export-canvas-to-svg-file
function tweakLib() {
  C2S.prototype.getContext = function(contextId) {
    if (contextId === '2d' || contextId === '2D') {
      return this;
    }
    return null;
  }
  C2S.prototype.style = function() {
    return this.__canvas.style;
  }
  C2S.prototype.getAttribute = function(name) {
    return this[name];
  }
  C2S.prototype.addEventListener = function(type, listener, eventListenerOptions) {
    // nothing to do here, but we need this function :)
  }
}


Chart.js - Schrift[Bearbeiten]

Schriftart muss auf der HTML Seite verfügbar sein. Geht also ganz normal mit Webschriften. Hat bei mir nicht mit allen geklappt. TTF hat funtioniert.

Schrift wurde z.T abgeschnitten. Hat aber geklappt wenn die Default Schrift so weit läuft wie die am Ende gerenderte. Ich nehme an er berechnet zuerst mit dem Standard den Platz. Man sieht auch wie die Schrift nachgeladen wird und plötzlich wechselt. Evtl. man dafür sorgen, dass die Schrift vorgeladen wird.

Definition über Default Werte:

Chart.defaults.font.family = \"'NotoSansSemiCondensed',Arial,'Helvetica Neue',sans-serif\";

Stil wird nicht in Affinity Designer erkannt (SVG Export)[Bearbeiten]

Damit die Schrift richtig erkannt wird kann man sie entweder in die SVG Grafik einbetten (kompliziert aber zuverlässig). Es reicht aber auch wenn man genau den richtigen Schriftnamen verwendet.

Beispiel: Noto Sans SemiCondensed Font in SVG Grafik[Bearbeiten]

HTML/CSS - Schrift so definieren, dass font-family genau den vom Grafikprogramm genutzten Namen nutzt. Im Zweifel testen. Evtl. auch erstmal ohne Stil dann ergänzen.

<style>
@font-face {
font-family: \'NotoSans-SemiCondensed\';
src: url(\'../fonts/NotoSans-SemiCondensed.ttf\') format(\'truetype\');
src: url(\'../fonts/Noto-Sans-SemiCondensed1.ttf.woff\') format(\'woff\');
font-weight: normal;
font-style: normal;
</style>

ChartJS Definition (hier als php Variable zum späteren Verwenden im Script).

$chartDefaults = "
Chart.defaults.font.size = 14;
Chart.defaults.color = '$dark';
Chart.defaults.font.family = \"'NotoSans-SemiCondensed',Arial,'Helvetica Neue',sans-serif\";
";