HTML5围绕它的中心点旋转文本 [英] HTML5 rotate text around it's centre point

查看:130
本文介绍了HTML5围绕它的中心点旋转文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些麻烦,我的画布中的一段文字,它的中心点,这里是我的代码尝试我的问题

I'm having some trouble rotating a piece of text in my canvas by it's centre point, here is my code to attempt my problem

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!
this.XPos = 65;
this.YPos = 100,

this.Text is just "Hello world!" this.XPos = 65; this.YPos = 100,

这是一张带有非旋转文字和旋转文字的图片,

我的中心点错了吗?

Here is a picture with the non-rotated text and rotated text, Am I working out the centre point wrong?

推荐答案

这里有一种方法:


  • c $ c> textAlign & textBaseline 以水平和垂直中心绘制文本:

  • Use textAlign & textBaseline to draw the text at it's horizontal and vertical center:

translate

translate to the x,y where you want the text centered.

旋转所需角度

最后 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; }
    canvas{border: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>

这篇关于HTML5围绕它的中心点旋转文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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