0

What are some efficient methods of finding the x,y coordinates of the right and bottom edges of a paragraph of text placed on a canvas element? So far attempts to multiply number of characters times font size have proved unreliable and more difficult than expected.

For example:

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText("Hello World, this is a sentence", 10, 50); 

I'd like to find the exact location of the bottom right corner of the sentence placed on canvas without having to calculate it dynamically based on the font size.

Schuyler Sloane
  • 359
  • 3
  • 17
  • what is the main goal? are you trying to find the area of the paragraph? are you trying to figure out how big you should make these paragraphs? – devin Oct 24 '22 at 16:32
  • Show some code where you draw the text. – kelsny Oct 24 '22 at 16:33
  • 1
    var rect = element.getBoundingClientRect(); console.log(rect.top, rect.right, rect.bottom, rect.left); Could you be looking for this? https://stackoverflow.com/questions/442404/retrieve-the-position-x-y-of-an-html-element – devin Oct 24 '22 at 16:35
  • @devin My main goal is to draw a rectangle background for the given text that is perfectly centered with a specific margin around the edges – Schuyler Sloane Oct 24 '22 at 16:36
  • @schquestioner there is no calculation needed for this make another tag that encapsulates the

    tag then use css on that tag, or just change the background color of the css on the p tag

    – devin Oct 24 '22 at 16:39
  • perhaps I am not understanding the question or goal, I think you need to produce a "minimal example" so that I can put your code into my system and test to see how to fix your problem – devin Oct 24 '22 at 16:41
  • @devin I'm using something like context.fillText("hello world", x,y) to place text on canvas, not html elements than can be encapsulated with

    tags.

    – Schuyler Sloane Oct 24 '22 at 16:44
  • @schquestioner show me with your code what you are doing, in the question – devin Oct 24 '22 at 16:59
  • 1
    you have to make sure the width and height of the canvas tag is equal to the size of the page then you can just do what I posted to get the bottom right cordinates – devin Oct 24 '22 at 17:32
  • 1
    Use the code In this answer: https://stackoverflow.com/a/60141000/3702797 (or [here](https://stackoverflow.com/a/67015797/3702797) in a more functionnal version) – Kaiido Oct 24 '22 at 23:20

0 Answers0