【问题标题】:Rotating multiple texts in canvas在画布中旋转多个文本
【发布时间】:2015-08-18 00:55:33
【问题描述】:

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

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

【问题讨论】:

  • 我已经关注了这个问题并使用了旋转和恢复...但它没有按预期工作
  • 如果您无法旋转文本,这种方法会很有用:if ( i % 2 == 0 ) { c.fillText(data.values[i].X, getXPixel(i), graph.height() - yPadding + 20); } else { c.fillText(data.values[i].X, getXPixel(i), graph.height() - yPadding + 10); }
  • 嘿,这很不错,jsfiddle.net/67tddgcj/2 ..但仍然旋转会让它看起来很好看..

标签: javascript html canvas


【解决方案1】:

您可以调整文本的角度,使其始终适合这样的图表:

  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;}
&lt;canvas id="canvas" width=300 height=300&gt;&lt;/canvas&gt;

【讨论】:

    猜你喜欢
    • 2013-04-06
    • 2014-01-18
    • 1970-01-01
    • 2011-03-11
    • 2015-10-22
    • 2017-08-06
    • 2011-08-10
    • 2014-11-09
    • 2014-02-01
    相关资源
    最近更新 更多