0

Casually i would detect the width and height of a string by doing this..

canvas.getContext("2d").font="12px Arial";
canvas.getContext("2d").fillStyle = "red";
canvas.getContext("2d").fillText("StackOverflow",x,y);

var width = canvas.getContext('2d').measureText(ct_string).width;

however, i need to calculate the width before i draw it into the canvas so i can do this..

canvas.getContext("2d").fillText("StackOverflow",x - width,y);

Would love some help on this, maybe i am not understanding the measureText fully, i believe it can only be used after the string has been drawn to the canvas though i am not certain.

( i am programming without a server and can not test the code i am running ). Creating a second html5 canvas is out of the question.

I need a better understanding

  • I think measure text takes the context font attribute from the context and calculates the width depending on that, rather than searching the html5 canvas for an object that contains the string "StackOverflow" – user3283552 May 10 '14 at 00:48
  • Sweet, i found a website that would let me test javascript. for anyone else who needs help.. here. Measure text takes the string argument and applies the font style and calculates the space that it will take when drawn. It does NOT search the html5 canvas element for the string. I wish the documentation would have said this :P – user3283552 May 10 '14 at 00:58
  • Searching the text in the canvas instead of directly calculating it would be too overkill, and imprecise. – Oriol May 10 '14 at 02:06
  • If you found the answer, post it as an answer, not comment. – Oriol May 10 '14 at 02:08
  • I cant post an answer to my own question yet. – user3283552 May 10 '14 at 07:19

0 Answers0