在 HTML5 画布上绘制旋转文本 [英] Drawing rotated text on a HTML5 canvas

查看:40
本文介绍了在 HTML5 画布上绘制旋转文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发的 Web 应用程序的一部分需要我创建条形图来显示各种信息.我想,如果用户的浏览器有能力,我会使用 HTML5 画布元素绘制它们.我为我的图形绘制线条和条形没有问题,但是在标记轴、条形或线条时,我遇到了障碍.如何将旋转的文本绘制到画布元素上,使其与它所标记的项目对齐?几个例子包括:

Part of a web application I'm developing requires me to create bar graphs to display various information. I figured, if the user's browser is capable, I would draw them using the HTML5 canvas element. I have no problem drawing lines and bars for my graphs, but when it comes to labeling the axes, the bars, or the lines I ran into a snag. How do I draw rotated text onto a canvas element so that it lines up with the item it is labeling? A couple examples include:

  • 将文本计数器旋转 90 度顺时针标记 y 轴
  • 将文本计数器旋转 90 度顺时针在垂直方向上标记条形条形图
  • 将文本任意旋转到在折线图上标记线

任何指针将不胜感激.

推荐答案

与其他人提到的一样,您可能希望重用现有的图形解决方案,但旋转文本并不太困难.有点令人困惑的一点(对我来说)是你旋转整个上下文然后在它上面绘制:

Like others have mentioned, you probably want to look at reusing an existing graphing solution, but rotating text isn't too difficult. The somewhat confusing bit (to me) is that you rotate the whole context and then draw on it:

ctx.rotate(Math.PI*2/(i*6));

角度在弧度.代码是 取自这个例子,我相信它是为 MDC 画布教程的转换部分.

The angle is in radians. The code is taken from this example, which I believe was made for the transformations part of the MDC canvas tutorial.

请参阅下面的答案以获得更完整的解决方案.

Please see the answer below for a more complete solution.

这篇关于在 HTML5 画布上绘制旋转文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆