Reputation: 1263
I am working with javascript / html and trying to fetch the text from a canvas object which is already created on the page.
I would like to click a button after the page is already loaded and see the text from the canvas object. Here is the code I am trying.
var CheckCanvas = document.getElementById(className);
var CheckContext = CheckCanvas.getContext('2d');
alert( 'btn text: ' + CheckContext.Text );
I have also tried fetching the 'fillText' property but I am unable to get the text from the object.
Any help would be much appreciated. I'm sure it's simple, but I could not find a solution.
Thanks.
Upvotes: 2
Views: 12065
Reputation: 3126
Okay. First of all, there is no way to do it using currently available canvas methods (or I am not aware of it). One way to do is to write your own class but that's a whole lot of work. I will suggest that you use a canvas library like kineticjs or fabricjs which will make it very easy to implement such function. Here's an example of how you can do it using fabricjs.
<canvas id="canvas1"></canvas>
<button id="addtext">Add Text </button>
<button id="retText">Retrive Text </button>
var canvas = new fabric.Canvas('canvas1');
document.getElementById('addtext').onclick = function() {
var textVar = new fabric.Text("Hello World!");
textVar.left=100;
textVar.top=100;
canvas.add(textVar);
};
document.getElementById('retText').onclick = function() {
var activeObject = canvas.getActiveObject();
if (activeObject && activeObject.type === 'text') {
alert(activeObject.text);
}
else
{
alert ("No object selected or Selected object not text");
}
};
Upvotes: 1
Reputation: 7407
You wont be able to get the text from a canvas object because it is a image.. You can however store the text in a variable before it have been drawed, and then output it later.
var text = "Hello";
conxtext.fillText(text, 100, 100);
alert("value: " + text);
Upvotes: 4
Reputation: 5709
See http://jsfiddle.net/ws5aK/
CheckContext.fillText
works, but there is no such property called Text
.
Upvotes: 0