我正在尝试在 HTML5 Canvas 中创建图形。但是 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();
但文字出现在不同的地方。
最佳答案
您可以调整文本的 Angular ,使其始终适合图形,如下所示:
- 保存起始上下文状态(未转换)
- 设置需要的字体
- 测量文本的像素宽度
- 转换为所需的端点
- 旋转到需要的 Angular
- 设置文本基线,使文本在端点上垂直居中
- 按负宽度绘制文本,使文本在所需端点结束
- R将上下文恢复到它的起始状态
这是示例代码和演示:
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();
}
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
<canvas id="canvas" width=300 height=300></canvas>
关于javascript - 在 Canvas 中旋转多个文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28560842/