简体   繁体   English

JavaScript / HTML5 - 获取画布对象文本?

[英]JavaScript / HTML5 - Fetch Canvas Object Text?

I am working with javascript / html and trying to fetch the text from a canvas object which is already created on the page. 我正在使用javascript / html并尝试从已在页面上创建的画布对象中获取文本。

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. 我也尝试获取'fillText'属性,但我无法从对象中获取文本。

Any help would be much appreciated. 任何帮助将非常感激。 I'm sure it's simple, but I could not find a solution. 我确信它很简单,但我找不到解决方案。

Thanks. 谢谢。

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);

Okay. 好的。 First of all, there is no way to do it using currently available canvas methods (or I am not aware of it). 首先,没有办法使用当前可用的canvas方法(或者我不知道它)。 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. 我建议您使用像kineticjs或fabricjs这样的画布库,这样可以很容易地实现这样的功能。 Here's an example of how you can do it using fabricjs. 这是一个如何使用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");
    }
  };

jsFiddle here. jsFiddle在这里。

See http://jsfiddle.net/ws5aK/ http://jsfiddle.net/ws5aK/

CheckContext.fillText works, but there is no such property called Text . CheckContext.fillText有效,但没有名为Text属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM