html5文本绘制,在HTML5画布上绘制旋转文本

虽然这是对前一个答案的跟进,但它增加了一点(希望如此) .

主要是我想澄清的是,通常我们会想到绘制像 draw a rectangle at 10, 3 这样的东西 .

所以如果我们这样考虑: move origin to 10, 3 ,那么 draw rectangle at 0, 0 . 然后我们要做的就是在两者之间添加一个旋转 .

另一个重点是文本的对齐 . 最简单的方法是在0,0处绘制文本,因此使用正确的对齐方式可以让我们在不测量文本宽度的情况下执行此操作 .

我们仍然应该将文本移动一定量以使其垂直居中,并且不幸的是画布没有很好的线高支持,所以这是一个猜测和检查的事情(如果有更好的东西,请纠正我) .

我创建了3个示例,提供了一个点和一个带有3个对齐的文本,以显示屏幕上的实际点是字体的位置 .

9be05ab9-3126-4939-a5a2-9333a946eace.png

var font, lineHeight, x, y;

x = 100;

y = 100;

font = 20;

lineHeight = 15; // this is guess and check as far as I know

this.context.font = font + 'px Arial';

// Right Aligned

this.context.save();

this.context.translate(x, y);

this.context.rotate(-Math.PI / 4);

this.context.textAlign = 'right';

this.context.fillText('right', 0, lineHeight / 2);

this.context.restore();

this.context.fillStyle = 'red';

this.context.fillRect(x, y, 2, 2);

// Center

this.context.fillStyle = 'black';

x = 150;

y = 100;

this.context.save();

this.context.translate(x, y);

this.context.rotate(-Math.PI / 4);

this.context.textAlign = 'center';

this.context.fillText('center', 0, lineHeight / 2);

this.context.restore();

this.context.fillStyle = 'red';

this.context.fillRect(x, y, 2, 2);

// Left

this.context.fillStyle = 'black';

x = 200;

y = 100;

this.context.save();

this.context.translate(x, y);

this.context.rotate(-Math.PI / 4);

this.context.textAlign = 'left';

this.context.fillText('left', 0, lineHeight / 2);

this.context.restore();

this.context.fillStyle = 'red';

this.context.fillRect(x, y, 2, 2);

this.context.fillText('right', 0, lineHeight / 2); 行基本上是 0, 0 ,除了我们略微移动文本在点附近居中

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值