开发者

HTML Canvas; Given two Xs and two Ys, Center Text within

I am making a series of rectangles. This is not the entire script, this code will actually be within a function with parameters for x and y coordinates and parameters for height and width. This function will be used to create multiple rectangles. My question is that I need to center the text within rectangles of x,y,width and height ... and the text will vary in length.


<!DOCTYPE html> 
<html lang="en">
<body>

<canvas id="myCanvas" width="400" height="350">
Your browser does not support the canvas element.
</canvas>

<script type="text/javascript">

    var x = 10;
    var y = 10;
    var width = 180;
    var height = 75;

    var c = document.getElementById("myCanvas");
    ctx = c.getContext("2d"); 


    ctx.lineWidth = 5;
    ctx.strokeStyle="black";    
    ctx.strokeRect(x,y,width,height);       

    ctx.textBaseline = 'top';  
    ctx.font    开发者_高级运维     = '20px Sans-Serif';
    ctx.fillStyle    = 'blue';
    ctx.fillText  ("hello", 30, 50);

</script>

</body>
</html>


You can use the measureText method of your context to calculate the position of your text before drawing it.


to center vertically use this:

context.textBaseline = "middle";

y_pos = text_area_height / 2;


Use the textAlign property:

context.textAlign = 'center';

http://www.html5canvastutorials.com/tutorials/html5-canvas-text-align/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜