我有这个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);
}
}
有什么想法吗?每个 Angular 色是否也可以有自己的旋转速度?
最佳答案
默认情况下,使用 textAlign='start'
和 textBaseline='alphabetic'
绘制文本。因此,fillText("g",20,50)
会向左绘制单个字符(在 x=20 处),并允许字符下伸部分降至 y=50 以下。
如果您想以指定的 [x,y] 为中心绘制文本,您可以设置 textAlign
和 textBaseline
。
// 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';
旋转 Angular 色:
context.translate
到所需的中心 x,y。context.rotate
至所需 Angular 。context.fillText(yourCharacter,0,0)
在 Canvas 上绘制字符。您在 0,0 处绘制,因为您已经使用context.translate
命令将原点移动到 x,y。
您可以使用 requestAnimationFrame 为 Angular 色的旋转设置动画。
将旋转 Angular 色的代码放入函数中:functionrotateCharacter()
。发送居中和旋转字符所需的参数:character
、centerX
、centerY
、radianAngle
。
然后创建另一个函数来为 Angular 色的旋转设置动画:function animate()
动画函数内部:
- 清除 Canvas :
context.clearRect
, - 调用旋转函数绘制旋转后的 Angular 色,
- 更新下一动画帧的旋转 Angular
- 请求动画继续:
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>
关于javascript - Canvas 中字体字符的几何旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36109309/