我正在尝试在HTML5画布中创建图形。但是x轴上的文本是重叠的。我试图旋转它看起来很整洁。
示例jsfiddle:http://jsfiddle.net/67tddgcj/1/
我尝试保存,旋转和恢复,如下所示
c.save();
c.rotate(-Math.PI/2);
c.fillText(data.values[i].X, getXPixel(i), graph.height() - yPadding + 20);
c.restore();
但文字出现在另一个地方。
答案 0 :(得分:3)
您可以对文字进行调整,使其始终符合以下图表:
以下是示例代码和演示:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
for(var i=0;i<10;i++){
var endingX=30+i*15;
drawRotatedText(endingX,50,-Math.PI/4,'Jan '+i,'9px verdana');
}
function drawRotatedText(endingX,centerY,radianAngle,text,font){
// save the starting context state (untransformed)
ctx.save();
// set the desired font
ctx.font=font;
// measure the pixel width of the text
var width=ctx.measureText(text).width;
// translate to the desired endpoint
ctx.translate(endingX,centerY);
// rotate to the desired angle
ctx.rotate(radianAngle);
// set the text baseline so the text
// is vertically centered on the endpoint
ctx.textBaseline='middle';
// draw the text offset by the negative width
// so the text ends at the desired endpoint
ctx.fillText(text,-width,0);
// restore the context to its starting state
ctx.restore();
}
&#13;
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
&#13;
<canvas id="canvas" width=300 height=300></canvas>
&#13;