Vijeta Karani
Vijeta Karani

Reputation: 95

How to retrive text written on canvas as string

I have written text on canvas using filltext(). Now in another function i want to retrieve that value as string. If anyone could help me please. Thanks in advance.

Upvotes: 1

Views: 1212

Answers (2)

nurettin
nurettin

Reputation: 11756

This w3c article might be of interest to you:

When an author renders text on a canvas with fillText or strokeText, they must also add an html element (div or span) with the same text, styling and position to the canvas subdom. The bounding box of the text should be set with the setElementPath method (See http://www.w3.org/wiki/Canvas_hit_testing)

This enables user agents to use the subdom text to deliver an accessible experience, as the subdom text acts as a proxy for the rendered text in the bitmap.

And here's an example built for accessibility:

<canvas id="example" width="260" height="200" role="img">   <p>A <a href="http://en.wikipedia.org/wiki/Rectangle">rectangle</a> with a black border. In the background is a pink circle. Partially overlaying the circle is a green square and a purple triangle, both of which are semi-opaque, so the full circle can be seen underneath.</p>   </canvas>

So all you need to do is when the user enters text, store it within a div inside the canvas element.

Upvotes: 1

Gareth Cornish
Gareth Cornish

Reputation: 4356

When you write the text to the canvas, also add a custom property to the canvas object containing the text itself. When you want to check it, simply query that property. So:

myCanvas.getContext("2d").filltext(theText,x,y,maxWidth);
myCanvas.addedText = theText;

And later,

var textToCheck = myCanvas.addedText;

Upvotes: 3

Related Questions