用文本填充画布形状 [英] filling a canvas shape with text

查看:125
本文介绍了用文本填充画布形状的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚如何将文字添加到画布形状
,例如这里是我的代码

i am trying to figure out how to add a text to a canvas shape for example here is my Code:

var text ="5"; // text to display over the circle
context.fillStyle = "red";
context.beginPath();
context.arc(50,70, 10, 0, Math.PI * 2);
context.closePath();
context.fill(); 

如果有人帮我将文字添加到形状
,我会非常喜欢它提前谢谢。

i would very much appriciate it if someone would help me adding the text to the shape thanks in advance.

编辑
i弄清楚我需要在画布上再写一次所以这就是我到目前为止所得到的...但
文本没有与圆圈的中心对齐:

EDIT i figure out that i need to write again on the canvas so this is what i got so far ... but the text doesnt allign to the center of the circle :

  context.fillStyle = "red";
  context.beginPath();
  var radius = 10; // for example
  context.arc(200, 200, radius, 0, Math.PI * 2);
  context.closePath();
  context.fill();
  context.fillStyle = "black"; // font color to write the text with
  var font = "bold " + radius +"px serif";
  context.font = font;
  context.textBaseline = "top";
  context.fillText(text, 200-radius/4 ,200-radius/2);


推荐答案

正如您在此处所见:

http://jsfiddle.net/DKcpS/

文本在圆圈的中心开始开始,从文本的顶部开始,因为你放了 textBaseline top

The text is getting drawn starting in the center of the circle, and starting with the top of the text since you put the textBaseline to top.

这是大致使用文本宽度和高度居中的文本:

This is the same text centered roughly using the width and height of the text:

http://jsfiddle.net/DKcpS/1/

如您所见,我们有一个 context.measureText(theTextToMeasure)函数,它返回 textMetrics 具有width属性的对象。现在它没有高度一,所以我们不得不猜测。

As you can see we have a context.measureText(theTextToMeasure) function that returns a textMetrics object that has a width property. For now it does not have a height one, so we have to sort of guess that.

这篇关于用文本填充画布形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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