プロジェクトにChart.jsを使用しています(http://www.chartjs.org/)。
タイトルやカスタム画像の追加、チャートへの「マージン」の追加など、実際のキャンバスに新しいものを描画する方法を誰かが知っていますか?
はい。
ChartJsのonAnimationComplete
コールバックを設定して、ChartJsが独自の描画とアニメーション化を完了したときに、カスタム描画コードを呼び出すことができます。
そのコールバックでは、canvas context
(== ChartJSに最初に入力したものと同じキャンバス/コンテキスト)を取得し、そのコンテキストを使用して、必要な新しいカスタムコンテンツを描画できます。
仕組みの例を次に示します。
ChartJSには、チャートコンテンツへのネイティブな「パディング」がありません。パディングを取得する1つの方法は、グラフを小さいメモリ内キャンバスに描画してから、そのメモリ内キャンバスをオフセットを使用して表示可能なキャンバスに描画し、目的のパディングを可能にすることです。
次に例を示します。
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]
コメントを追加