HTML Canvas Given two Xs and two Ys, Center Text inside

I make a series of rectangles. This is not the whole script, this code will actually be in 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 inside the rectangles of x, y, width and height ... and the text will change 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>
+3
source share
3 answers

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

+5
source

, :

context.textBaseline = "middle";

y_pos = text_area_height / 2;
+2
0

All Articles