canvas 中字体字符的几何旋转

Geometric rotation of font character in canvas

我有这个 codepen,我想做的是在翻译时在其中心点平滑地旋转每个字体字符。我是 canvas 世界的新手,我真的不知道如何做到这一点。

我这样试过,但它的行为似乎很奇怪:

Draw: function () {
                //tried to add this line :
               context.rotate(Math.PI / 4);

                context.font = this.size + "px FontAwesome";
                context.fillStyle = this.color;
                context.strokeStyle = this.color;
                if (this.id % 2 == 0) {
                    context.fillText(this.icon, this.x, this.y);
                } else {
                    context.strokeText(this.icon, this.x, this.y);
                }
            }

有什么想法吗?是不是每个角色都有自己的旋转速度?

默认情况下,文本使用 textAlign='start'textBaseline='alphabetic' 绘制。因此 fillText("g",20,50) 将您的单个字符向左对齐(在 x=20 处)并允许字符下降低于 y=50。

如果您想以指定的 [x,y] 为中心绘制文本,您可以设置 textAligntextBaseline

// text will be horizontally centered around the specified x in filltext
textAlign='center';

// text will be vertically centered around the specified y in filltext
textBaseline='middle';

要旋转角色:

  1. context.translate 到所需的中心 x,y。
  2. context.rotate到所需的角度。
  3. context.fillText(yourCharacter,0,0)在canvas上绘制字符。您在 0,0 处绘制,因为您已经使用 context.translate 命令将原点移动到 x,y。

您可以使用 requestAnimationFrame 来设置角色旋转的动画。

将旋转角色的代码放入函数中:function rotateCharacter()。发送居中和旋转角色所需的参数:charactercenterXcenterYradianAngle.

然后创建另一个动画角色旋转的函数:function animate()

动画函数内部:

  1. 清除 canvas: context.clearRect,
  2. 调用旋转函数绘制旋转后的字符,
  3. 更新下一动画帧的旋转角度
  4. 请求动画继续:requestAnimationFrame

这是示例代码和演示:

// canvas vars
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

// set canvas text styling
ctx.font='30px verdana';
ctx.textAlign='center';
ctx.textBaseline='middle';

// character vars
var character='M';
var centerX=50;
var centerY=50;
var radianAngle=0;

// start animating
requestAnimationFrame(animate);


function rotateCharacter(text,centerX,centerY,radianAngle){
    // translate to the centerpoint you desire to rotate around
    ctx.translate(20,50);
    // rotate by the desired angle
    ctx.rotate(radianAngle);
    // draw the text on the canvas
    ctx.fillText('M',0,0);
    // always clean up -- reset transformations to default
    ctx.setTransform(1,0,0,1,0,0);
}

function animate(time){
    // clear the canvas
    ctx.clearRect(0,0,cw,ch);
    // draw the character rotated & centered at centerX,centerY
    rotateCharacter(character,centerX,centerY,radianAngle);
    // update the rotation angle for next time
    radianAngle+=Math.PI/45;
    // request another animation frame
    requestAnimationFrame(animate);
}
body{ background-color: ivory; }
#canvas{border:1px solid blue; margin:0 auto; }
<h4>A character rotating around a specified centerpoint</h4>
<canvas id="canvas" width=300 height=300></canvas>