HTML5 围绕其中心点旋转文本

Posted

技术标签:

【中文标题】HTML5 围绕其中心点旋转文本【英文标题】:HTML5 rotate text around it's centre point 【发布时间】:2014-09-30 02:29:23 【问题描述】:

我在将画布中的一段文本按其中心点旋转时遇到了一些问题,这是我尝试解决问题的代码

var textPositions = context.measureText(this.Text);

    context.save();

    context.translate(this.XPos + (textPositions.width / 2), this.YPos);
    context.rotate( (Math.PI / 180) * this.RotateSpeed );
    context.font = this.FontSize + "px " + this.FontStyle;
    context.fillText(this.Text, 0, 0);
    context.translate(-(this.XPos + (textPositions.width / 2)), -(this.YPos));

    context.restore();

this.Text 只是“Hello world!” 这个.XPos = 65; this.YPos = 100,

这是一张带有非旋转文本和旋转文本的图片, 我算错了中心点吗?

【问题讨论】:

它似乎围绕左下角(H 的底部)旋转。有关相关讨论和答案,请参阅 ***.com/questions/3167928/…。 【参考方案1】:

这是一种方法:

使用textAlign & textBaseline在水平和垂直中心绘制文字:

translate 到您希望文本居中的 x,y。

rotate 所需的角度

最后是fillText

示例代码和演示:http://jsfiddle.net/m1erickson/uL62et9y/

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
    body background-color: ivory; 
    canvasborder:1px solid red;
</style>
<script>
$(function()

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    var cw=canvas.width;
    var ch=canvas.height;

    ctx.beginPath();
    ctx.moveTo(cw/2,0);
    ctx.lineTo(cw/2,ch);
    ctx.stroke();
    ctx.beginPath();
    ctx.moveTo(0,ch/2);
    ctx.lineTo(cw,ch/2);
    ctx.stroke();

    ctx.save();

    ctx.textAlign="center";
    ctx.textBaseline="middle";

    ctx.translate(150,150);
    ctx.rotate(Math.PI/2);
    ctx.fillText("Hello World!",0,0);

    ctx.restore();

); // end $(function());
</script>
</head>
<body>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

【讨论】:

是的,我只需要 "context.textAlign = "center";" :) 为答案喝彩

以上是关于HTML5 围绕其中心点旋转文本的主要内容,如果未能解决你的问题,请参考以下文章

SVG css旋转坚持而不是围绕中心旋转

在THREE.js中围绕自己的中心旋转每个网格项目

使用鼠标围绕中心旋转 Three.js 相机

如何相对于其中心点旋转或缩放(变换)SVG 路径?

围绕特定轴旋转 gluCylinder()?

如何围绕对象外部的点旋转节点(即不围绕对象的中心点旋转)