Categories
Chart.js

Chart.js — Options

We can make creating charts on a web page easy with Chart.js.

In this article, we’ll look at how to create charts with Chart.js.

Printing Resizable Charts

We can add an event handler for the beforeprint event to trigger the resizing of the charts before we print them.

For example, we can write:

window.onbeforeprint = () => {
  for (const id in Chart.instances) {
    Chart.instances[id].resize();
  }
}

to add the beforeprint handler and resize all the chart instances that are found with Chart.instances .

Events

We can set which events a chart responds to.

For example, we can add the options.event property with an array of event name strings to set the events it responds to:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Red', 'Blue', 'Yellow'],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
      ],
      borderColor: [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
      ],
      borderWidth: 1
    }]
  },
  options: {
    events: ['click'],
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

We have the ['click'] array so that it only respond to click events.

Interaction Modes

We can configure the interaction of tooltips.

For example, we can write:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Red', 'Blue', 'Yellow'],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
      ],
      borderColor: [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
      ],
      borderWidth: 1
    }]
  },
  options: {
    tooltips: {
      mode: 'point'
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

to find all the items that intersect the point.

We can get the items that are nearest to the point with the 'nearest' value.

This means that the tooltip is only triggered when the mouse position intersects an item in the graph.

Scriptable Options

We can set scriptable options with a function.

For example, we can change the color option dynamically by writing:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Red', 'Blue', 'Yellow'],
    datasets: [{
      label: '# of Votes',
      data: [-1, 19, 3],
      backgroundColor(context) {
        var index = context.dataIndex;
        var value = context.dataset.data[index];
        return value < 0 ? 'red' :
          index % 2 ? 'blue' :
          'green';
      },
      borderColor: [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
      ],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

We changed the background colors of the bars with the backgroundColor options.

index has the index of the graph.

value has the value of the y-axis.

So if value , we show red.

Otherwise, we alternate between blue and green.

Conclusion

We can change various options with Chart.js.

Also, we can resize charts to fit when we print them.

Categories
Chart.js

Chart.js — Fonts and Performance

We can make creating charts on a web page easy with Chart.js.

In this article, we’ll look at how to create charts with Chart.js.

Fonts

We can change the font settings by setting the options.legend.labels.fontColor properties.

For example, we can write:

Chart.defaults.global.defaultFontColor = 'red';

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Red', 'Blue', 'Yellow'],
    datasets: [{
      label: '# of Votes',
      data: [2, 19, 3],
      backgroundColor: [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
      ],
      borderColor: [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
      ],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    },
    legend: {
      labels: {
        fontColor: 'green'
      }
    }
  }
});

to change the color globally with the Chart.defaults.global.defaultFontColor property.

And we change the legend text’s color with the options.legend.labels.fontColor property.

Rotation

We can set the minRotation and maxRotation properties to the same value to avoid charts from having to automatically determine a value to use.

Sampling

Also, we can set the ticks.sampleSize option to determine how large our labels are by looking at a subset of them to render the axes faster.

Disable Animations

We can disable animations with the animation , responsiveAnimationDuration, and hover options.

For example, we can write;

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Red', 'Blue', 'Yellow'],
    datasets: [{
      label: '# of Votes',
      data: [2, 19, 3],
      backgroundColor: [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
      ],
      borderColor: [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
      ],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    },
    animation: {
      duration: 0
    },
    hover: {
      animationDuration: 0
    },
    responsiveAnimationDuration: 0
  }
});

to disable all the animations with the options property.

Disable Bezier Curves in Line Charts

We can disable bezier curves in a line charts since drawing a straight line is faster than with a bezier curve.

We can do that with:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'line',
  options: {
    elements: {
      line: {
        tension: 0
      }
    }
  },
  data: {
    labels: ['Red', 'Blue', 'Yellow'],
    datasets: [{
      label: '# of Votes',
      data: [2, 19, 3],
      borderColor: [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
      ],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

The options.eleemnts.line.tension property disables drawing a bezier curve.

Disable Line Drawing

We can also disable lien drawing with the showLines property in the datasets or options properties.

For example, we can write:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ['Red', 'Blue', 'Yellow'],
    datasets: [{
      showLine: false,
      label: '# of Votes',
      data: [2, 19, 3],
      borderColor: [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
      ],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

to disable it for a dataset.

Conclusion

We can change the fonts with Chart.js.

Also, we can disable various animations and drawing to increase rendering performance.

Categories
Chart.js

Chart.js — Color Options

We can make creating charts on a web page easy with Chart.js.

In this article, we’ll look at how to create charts with Chart.js.

Indexable Options

Indexable options are options that are arrays.

For example, we can write:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Red', 'Blue', 'Yellow'],
    datasets: [{
      label: '# of Votes',
      data: [-1, 19, 3],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
      ],
      borderColor: [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
      ],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

We have the backgroundColor and borderColor options which are indexable options.

The values are set on the bars according to the bars’ indexes.

Option Context

The option content gives us contextual information when we resolving options.

They are used only with scriptable options.

The properties of the context object include:

  • chart — the chart we’re modifying
  • dataIndex — index of the current data
  • dataset — dataset at index datasetIndex
  • datasetIndex — index of the current dataset
  • hover — true if hovered

Colors

We can set the color options in various ways.

One way is to change the background color to a fill pattern.

For example, we can write:

var img = new Image();
img.src = 'https://www.toptal.com/designers/subtlepatterns/patterns/more-leaves.png';

img.onload = function() {
  var ctx = document.getElementById('myChart').getContext('2d');
  var fillPattern = ctx.createPattern(img, 'repeat');
  var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
      labels: ['Red', 'Blue', 'Yellow'],
      datasets: [{
        label: '# of Votes',
        data: [2, 19, 3],
        backgroundColor: fillPattern,
        borderColor: [
          'rgba(255, 99, 132, 1)',
          'rgba(54, 162, 235, 1)',
          'rgba(255, 206, 86, 1)',
        ],
        borderWidth: 1
      }]
    },
    options: {
      scales: {
        yAxes: [{
          ticks: {
            beginAtZero: true
          }
        }]
      }
    }
  });
};

We created an Image instance and we called the createPattern method of the context to create a fill pattern that we can use in our chart bars.

'repeat' makes the pattern repeat to fill the bars.

Then we set that as the value of backgroundColor and it’ll show as the bar color.

Also, we can use the Patternomaly library to create our patterns.

We can use it with the following HTML:

<script src='https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js'></script>

<script src="https://cdn.jsdelivr.net/npm/patternomaly@1.3.2/dist/patternomaly.min.js"></script>

<canvas id="myChart"></canvas>

Then we can create a chart by writing:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Red', 'Blue', 'Yellow'],
    datasets: [{
      label: '# of Votes',
      data: [2, 19, 3],
      backgroundColor: [
        pattern.draw('square', '#ff6384'),
        pattern.draw('circle', '#36a2eb'),
        pattern.draw('diamond', '#cc65fe'),
      ],
      borderColor: [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
      ],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

The pattern.draw method comes from the Patternomaly library.

'square' makes a square repeating pattern.

'circle' makes a circle repeating pattern.

And 'diamond' makes a diamond repeating pattern.

The 2nd argument is the background color.

Now we should see bars with the given background patterns.

Conclusion

We can create charts with various color options with Chart.js.

Categories
Chart.js

Getting Started with Chart.js

We can make creating charts on a web page easy with Chart.js.

In this article, we’ll look at how to create charts with Chart.js.

Installation

We can add the Chart.js library from CDN.

To do that, we write:

<script src='https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js'></script>

in our HTML.

Also, we can install the NPM package version by running:

npm install chart.js --save

The Bower package can be installed by running:

bower install chart.js --save

Creating a Chart

We can then create a chart by creating our canvas element:

<canvas id="myChart" width="400" height="400"></canvas>

And then we can add our JavaScript code for the graph:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Red', 'Blue', 'Yellow'],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
      ],
      borderColor: [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
      ],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

We get the canvas element’s context.

Then we use the Chart constructor to create our chart.

type has the chart type.

label has the legend label.

The labels property has the x-axis labels.

datasets has the data for the chart.

data has the y-axis cooredinates.

backgroundColor has the background color for the bars.

borderColor has the border color for the bars.

borderWidth has the border width.

options has some options for the graph.

scales has the graph scales.

We have the beginAtZero option set to true so that the y-axis starts at 0.

Accessible Charts

We can make our charts accessible with the aria-label and role attributes.

For example, we can write:

<canvas id="myChart" width="400" height="400" aria-label="bar chart" role="img"></canvas>

We can add fallback content with:

<canvas id="myChart" width="400" height="400" aria-label="bar chart" role="img">
  <p>fallback</p>
</canvas>

Responsive Charts

Charts can be made responsive with a wrapper element.

We style that remove the height and width from the canvas and put that in the wrapper element.

For instance, we can write:

<div class="chart-container" style="position: relative; height:40vh; width:80vw">
  <canvas id="myChart"></canvas>
</div>

We put the styles in the div instead of the canvas.

Now the chart should resize when we resize the screen.

The chart can also be programmatically resized:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Red', 'Blue', 'Yellow'],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
      ],
      borderColor: [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
      ],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

myChart.canvas.parentNode.style.height = '428px';
myChart.canvas.parentNode.style.width = '428px';

We changed the canvas’ parent node’s height and width.

Conclusion

We can create a simple chart with Chart.js with some JavaScript code.

Categories
Restify

Restify — Error Handling with Restify-Errors

Restify is a simple Node back end framework.

In this article, we’ll look at how to format error messages with Restify.

Formatting Errors

We can format errors with the error handler.

For example, we can write:

var restify = require('restify');
var errors = require('restify-errors');

var server = restify.createServer();

server.get('/hello/:foo', function(req, res, next) {
  var err = new errors.InternalServerError('not found');
  return next(err);
});

server.on('InternalServer', function (req, res, err, cb) {
  err.toString = function() {
    return 'an internal server error occurred!';
  };

  err.toJSON = function() {
    return {
      message: 'an internal server error occurred!',
      code: 'error'
    }
  };

  return cb();
});

server.on('restifyError', function (req, res, err, cb) {
  return cb();
});

server.listen(8080);

We have the InternalServer handler with the toString and toJSON methods to format string and JSON errors.

The restifyError error handler has the error handler.

Also, we can create formatters for other content types.

For example, we can write:

var restify = require('restify');
var errors = require('restify-errors');

const server = restify.createServer({
  formatters: {
    ['text/html'](req, res, body) {
      if (body instanceof Error) {
        return `<html><body>${body.message}</body></html>`;
      }
    }
  }
});

server.get('/', function(req, res, next) {
  res.header('content-type', 'text/html');
  return next(new errors.InternalServerError('error!'));
});

server.listen(8080);

to create a content formatter for the text/html content type.

restify-errors

The restify-errors module exposes a suite of error constrictors for many common HTTP requests and REST related errors.

For example, we can create errors by writing:

var restify = require('restify');
var errors = require('restify-errors');

const server = restify.createServer();

server.get('/', function(req, res, next) {
  return next(new errors.ConflictError("conflict"));
});

server.listen(8080);

Then when we go to http://localhost:8080 , we get:

{"code":"Conflict","message":"conflict"}

We can also pass in Restify errors as an argument of res.send .

For example, we can write:

var restify = require('restify');
var errors = require('restify-errors');

const server = restify.createServer();

server.get('/', function(req, res, next) {
  res.send(new errors.GoneError('gone'));
  return next();
});

server.listen(8080);

We pass in the GoneError instance into the res.send method.

Then when we go to http://localhost:8080 , we get:

{"code":"Gone","message":"gone girl"}

The automatic serialization to JSON is done by calling JSON.stringify on the Error object.

They all have the toJSON method defined.

If the object doesn’t have the toJSON method defined, then we would get an empty object.

HttpError

HttpError is a generic HTTP error that we can return with the statusCode and body properties.

The statusCode will be automatically set with the HTTP status code, and the body will be set to the message by default.

All status codes between 400 error 500s are automatically be converted to an HttpError with the name being in PascalCase and spaces removed.

RestError

Restify provides us with built it errors with the code and message properties/

For example, if we have:

var restify = require('restify');
var errors = require('restify-errors');

const server = restify.createServer();

server.get('/', function(req, res, next) {
  return next(new errors.InvalidArgumentError("error"));
});

server.listen(8080);

Any 400 or 500 series errors can be created with restify-errors .

Conclusion

We can create error objects with restify-errors .

They’ll be automatically be serialized into JSON if we use it in our response.