在 canvas 中旋转多个文本

Rotating multiple texts in canvas

我正在尝试在 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();

但是文字出现在不同的地方。

您可以调整文字的角度,使其始终适合图形,如下所示:

  1. 保存起始上下文状态(未转换)
  2. 设置所需的字体
  3. 测量文本的像素宽度
  4. 转换为所需的端点
  5. 旋转到所需角度
  6. 设置文本基线,使文本在端点上垂直居中
  7. 按负宽度绘制文本,使文本在所需端点结束
  8. 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>