Chart.js添加自定义标题,副标题,图形

时间:2015-03-13 19:02:38

标签: javascript html5 canvas charts

我正在将Chart.js用于项目(http://www.chartjs.org/)。

有人知道如何在实际画布上绘制新内容,比如标题或添加自定义图像,在图表中添加“边距”吗?

1 个答案:

答案 0 :(得分:4)

enter image description here

当ChartJs完成自己的绘图和动画时,您可以设置ChartJs的onAnimationComplete回调来调用您的自定义绘图代码。

在该回调中,您可以获得canvas context(==您最初输入ChartJS的相同画布/上下文)并使用该上下文绘制您想要的任何新自定义内容。

以下是其工作原理的示例:

Inserting percentage charts.js doughnut

ChartJS没有对其图表内容进行原生“填充”。获取一些填充的一种方法是将图表绘制到较小的内存中画布,然后将内存中的画布绘制到可见的画布上,并使用偏移量来填充所需的填充。

以下是一个例子:

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>