How to draw text on html-5 canvas given bottom right x,y

Viewed 1467

Does anyone know how to draw text on a html-5 canvas given its bottom right x,y coordinates? The .fillText("text", x, y) draws the text's top left corner at x,y I need it to draw the bottom right corner at x,y. If anyone knows the answer that would be very helpful.

3 Answers

get the width by using the measure text width

var width = ctx.measureText("text");

and (if you require it) you can get the approximate height by using your font size

ctx.font = "25px serif";
var height = parseInt(ctx.font.substring(0, 2)); // gets the font size

and since it renders bottom left, you just need to minus it

ctx.fillText("text", x - width, y);

Use the measureText() function.

const width = context.measureText("text").width;
const height = context.measureText("text").height;
context.fillText("text", x - width, y - height);

Use textAlign. I had the same issue and did below and it worked for me.

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="500" height="1200" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

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


const x = c.width
const y = c.height
ctx.font = "15px Arial";    

// Show the different textAlign values
           
ctx.textAlign = "end";      
ctx.fillText("textAlign=end", x-10, y-10);
</script>

</body>
</html>

Related