javascript-Chart.js添加自定义标题,字幕,图形

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

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

解决方法:

是.

您可以设置ChartJs的onAnimationComplete回调以在ChartJs完成其自己的绘图和动画处理后调用自定义绘图代码.

在该回调中,您可以获得画布上下文(==您最初输入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>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。