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
measureTextmethod of your context to calculate the position of your text before drawing it.