Ahmed
Ahmed

Reputation: 37

Chart.js add custom title, subtitle, graphics

I'm using Chart.js for a project (http://www.chartjs.org/).

Does somebody know how to draw on the actual canvas new stuff, like a title or add custom images, add 'margin' to the chart?

Upvotes: 3

Views: 4996

Answers (1)

markE
markE

Reputation: 105015

Yes.

enter image description here

You can set ChartJs's onAnimationComplete callback to call your custom drawing code when ChartJs has completed it's own drawing and animating.

In that callback you can get the canvas context (== the same canvas/context that you originally fed into ChartJS) and use that context to draw whatever new custom content you desire.

Here's an example of how it works:

Inserting percentage charts.js doughnut

ChartJS does not have a native "padding" to its chart content. One way to get some padding is to draw the chart to a smaller in-memory canvas and then draw that in-memory canvas to your visible canvas with an offset to allow for your desired padding.

Here's a example:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

var pieData = [
  {
    value: 200,
    color:"#F7464A",
    highlight: "#FF5A5E",
    label: "Red"
  },
  {
    value: 50,
    color: "#46BFBD",
    highlight: "#5AD3D1",
    label: "Green"
  },
  {
    value: 100,
    color: "#FDB45C",
    highlight: "#FFC870",
    label: "Yellow"
  },
  {
    value: 40,
    color: "#949FB1",
    highlight: "#A8B3C5",
    label: "Grey"
  },
  {
    value: 120,
    color: "#4D5360",
    highlight: "#616774",
    label: "Dark Grey"
  }

];

// create an in-memory canvas (c) 
var c = document.createElement("canvas");

// size it to your desired size (without padding)
c.width=100;
c.height=100;

// make it hidden
c.style.visibility='hidden';
document.body.appendChild(c);

// create the chart on the in-memory canvas
var cctx = c.getContext("2d");
window.myPie = new Chart(cctx).Pie(pieData,{
  responsive:false,
  animation:false,


  // when the chart is fully drawn,
  // draw the in-memory chart to the visible chart
  // allowing for your desired padding
  // (this example pads 100 width and 50 height
  onAnimationComplete:function(){
    ctx.drawImage(c,100,50);
    ctx.fillText('Space to add something here with 50x100 padding',5,20);
    ctx.fillText('Added Padding',5,90);
    ctx.beginPath();
    ctx.moveTo(0,100);
    ctx.lineTo(100,100);
    ctx.stroke();
  }
});
body{ background-color: ivory; }
canvas{border:1px solid red;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script>
<canvas id="canvas" width=300 height=300></canvas>

Upvotes: 4

Related Questions