filling a canvas shape with text

那年仲夏 提交于 2019-12-19 03:59:32

问题


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.

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);

回答1:


As you can see here:

http://jsfiddle.net/DKcpS/

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/

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.



来源:https://stackoverflow.com/questions/10260176/filling-a-canvas-shape-with-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!