DEV Community

Dhruv Raval
Dhruv Raval

Posted on • Originally published at dhruvraval.dev on

Creating a Rough Chart with Chart.js and Rough.js

Chart.js is a popular JavaScript library that enables the creation of various types of charts.

Check this example to explore how to use Rough.js with Chart.js, a library that adds a hand-drawn, sketchy effect to charts. You can also use the custom font for chart.

I am using "Indie Flower" font. You can add your font from google.

HTML

<!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Indie+Flower"><link rel="stylesheet" href="./style.css">
</head>
<body>

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

<div class="slidecontainer">
  <h4>Roughness</h4>
  <input type="range" min="0" max="10" value="1" class="slider" id="rnSlider">
</div>

<script src='https://cdn.jsdelivr.net/npm/chart.js@2.8.0'></script>
<script src='https://cdn.jsdelivr.net/npm/roughjs@3.1.0/dist/rough.js'></script>
<script src='https://cdn.jsdelivr.net/npm/chartjs-plugin-rough@0.2.0'></script>

</body>
</html>

Enter fullscreen mode Exit fullscreen mode

Script

Chart.defaults.global.defaultFontFamily = '"Indie Flower", cursive';
Chart.defaults.global.defaultFontSize = 14;

var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['January', 'February', 'March', 'April', 'May', 'June'],
    datasets: [{
      data: [45, 20, 64, 32, 76, 51],
      backgroundColor: 'rgb(255, 99, 132)',
      borderColor: 'rgb(255, 99, 132)',
      borderWidth: 1,
      label:"Orders"
    }]
  },
  plugins: [ChartRough],
  options:{
    plugins:{
      rough: {
        roughness:1,
      }
    }
  }
});

var slider = document.getElementById("rnSlider");
slider.oninput = function() {
  chart.options.plugins.rough.roughness = this.value;
  chart.update()
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)