ChartJs是一款輕量級圖表工具,採用html5實現畫圖,convas對象的fillText只支持純文本, 所以連換行也不支持。如果要自定義tooltipTemplate,比如增加換行等,可以覆蓋其原始方法draw,非常簡單。如果要更復雜的,可能還得想其他辦法,不採用convas實現。
Chart.defaults.global.scaleBeginAtZero = true;
Chart.defaults.global.tooltipTemplate="<%= label %>#Pageview:<%= value %>";
//Chart.defaults.global.tooltipTemplate= "<%= label %>:<%= value %>";
var Gdate= {};
Chart.Tooltip = Chart.Element.extend({
draw : function(){
var ctx = this.chart.ctx;
ctx.font = Chart.helpers.fontString(this.fontSize,this.fontStyle,this.fontFamily);
this.xAlign = "center";
this.yAlign = "above";
//Distance between the actual element.y position and the start of the tooltip caret
var caretPadding = 2;
var tooltipWidth = ctx.measureText(this.text).width/2 + 2*this.xPadding+ 130,
tooltipRectHeight = 2*this.fontSize + 4*this.yPadding,
tooltipHeight = tooltipRectHeight + this.caretHeight + caretPadding;
if (this.x + tooltipWidth/2 >this.chart.width){
this.xAlign = "left";
} else if (this.x - tooltipWidth/2 < 0){
this.xAlign = "right";
}
if (this.y - tooltipHeight < 0){
this.yAlign = "below";
}
var tooltipX = this.x - tooltipWidth/2,
tooltipY = this.y - tooltipHeight;
ctx.fillStyle = this.fillColor;
switch(this.yAlign)
{
case "above":
//Draw a caret above the x/y
ctx.beginPath();
ctx.moveTo(this.x,this.y - caretPadding);
ctx.lineTo(this.x + this.caretHeight, this.y - (caretPadding + this.caretHeight));
ctx.lineTo(this.x - this.caretHeight, this.y - (caretPadding + this.caretHeight));
ctx.closePath();
ctx.fill();
break;
case "below":
tooltipY = this.y + caretPadding + this.caretHeight;
//Draw a caret below the x/y
ctx.beginPath();
ctx.moveTo(this.x, this.y + caretPadding);
ctx.lineTo(this.x + this.caretHeight, this.y + caretPadding + this.caretHeight);
ctx.lineTo(this.x - this.caretHeight, this.y + caretPadding + this.caretHeight);
ctx.closePath();
ctx.fill();
break;
}
switch(this.xAlign)
{
case "left":
tooltipX = this.x - tooltipWidth + (this.cornerRadius + this.caretHeight);
break;
case "right":
tooltipX = this.x - (this.cornerRadius + this.caretHeight);
break;
}
Chart.helpers.drawRoundedRectangle(ctx,tooltipX,tooltipY,tooltipWidth,tooltipRectHeight,this.cornerRadius);
ctx.fill();
ctx.fillStyle = this.textColor;
ctx.textAlign = "left";
ctx.textBaseline = "middle";
//ctx.fillText(this.text, tooltipX + tooltipWidth/2, tooltipY + tooltipRectHeight/2);
//alert(this.text);
var arr= this.text.split("#");
var date= getDate(arr[0]);
ctx.fillText("1. "+date, tooltipX + 10, tooltipY + 15);
ctx.fillText("2. "+arr[1], tooltipX + 10, tooltipY + tooltipRectHeight/2+ 10);
}
});