Diferencia entre revisiones de «Referencia:JavaScript»

De GeoGebra Manual
Saltar a: navegación, buscar
Línea 589: Línea 589:
 
<table style="width: 100%;" class="pretty">
 
<table style="width: 100%;" class="pretty">
 
     <tr>
 
     <tr>
       <th>Method Signature</th>
+
       <th>Método de Firma (Signature)</th>
       <th>Since</th>
+
       <th>Desde</th>
       <th>Description</th>
+
       <th>Descripción</th>
 
     </tr>
 
     </tr>
 
     <tr>
 
     <tr>
 
       <td>String evalMathPiper(String string) </td>
 
       <td>String evalMathPiper(String string) </td>
 
       <td style="text-align: center;">3.2</td>
 
       <td style="text-align: center;">3.2</td>
       <td>Passes the string to MathPiper and returns the result as a String.<br>
+
       <td>Pasa la cadena a MathPiper y establece el resultado como una Cadena.<br>
<b>Removed in GeoGebra 4.0 and will replaced with evalGeoGebraCAS() in GeoGebra 4.2</b>
+
<b>Eliminado en GeoGebra 4.0 y será reemplazado con evalGeoGebraCAS() wn GeoGebra 4.2</b>
 
       </td>
 
       </td>
 
     </tr>
 
     </tr>
Línea 603: Línea 603:
 
       <td>String getIPAddress()</td>
 
       <td>String getIPAddress()</td>
 
       <td style="text-align: center;">3.2</td>
 
       <td style="text-align: center;">3.2</td>
       <td>Returns the IP address of the local computer as a String eg "192.168.0.4"
+
       <td>Da por resultado la dirección de IP de la computadora local como una Cadena; por ejemplo, "192.168.0.4"
 
       </td>
 
       </td>
 
     </tr>
 
     </tr>
Línea 609: Línea 609:
 
       <td>String getHostname() </td>
 
       <td>String getHostname() </td>
 
       <td style="text-align: center;">3.2</td>
 
       <td style="text-align: center;">3.2</td>
       <td>Returns the hostname of the local computer as a String
+
       <td>Da por resultado el nombre del ''host'' de la computadora local como una Cadena
 
       </td>
 
       </td>
 
     </tr>
 
     </tr>
Línea 615: Línea 615:
 
       <td>void debug(String string) </td>
 
       <td>void debug(String string) </td>
 
       <td style="text-align: center;">3.2</td>
 
       <td style="text-align: center;">3.2</td>
       <td>Prints the string to the Java Console
+
       <td>Imprime la cadena de la Consola Java
 
       </td>
 
       </td>
 
     </tr>
 
     </tr>

Revisión del 04:27 2 ene 2012

Este documento describe métodos públicos disponibles en geogebra.GeoGebraApplet que pueden emplearse desde una página HTML vía JavaScript.

Ejemplos

Ejemplo 1: el siguiente fragmento de código HTML añade un botón de reinicio ("Reset") a una página HTML que permite reiniciar la construcción expuesta en el Applet de GeoGebra para que recupere su estado inicial:

 <form>
   <input type="button" value="Reset" onclick="document.applets[0].reset();">
 </form>

Ejemplo 2: esto añade dos botones "Oculta A" y "Expone A" cambia el estado de visibilidad de un objeto llamado "A" en la construcción

 <form>
   <input type="button" value="Oculta A" onclick="document.applets[0].setVisible('A', false);">
   <input type="button" value="Expone A" onclick="document.applets[0].setVisible('A', true);">
 </form>

Ejemplo 3: una función JavaScript "myLittleConstruction()" se emplea para llamar varios métodos del Applet de GeoGebra. Nota: se fija el idioma al Alemán ("de") con el parámetro "language" del applet en la etiqueta para asegurarse que el comando en alemán "Gerade" (línea) pueda operar.

 <applet name="ggbApplet" code="geogebra.GeoGebraApplet"
   archive="geogebra.jar"
   codebase="http://jars.geogebra.org/webstart/4.0/unsigned/"
   width=200 height=40>
 <param name="filename" value="circle.ggb">
 <param name="framePossible" value="false">
 <param name="language" value="de">
 Please <a href="http://www.java.com">install Java 1.4.2</a> (or later) to use this page.
 </applet>
 <script type="text/javascript">
   function myLittelConstruction() {
     var applet = document.ggbApplet;
     applet.evalCommand("A = (1,1)"); 
     applet.evalCommand("B = (3,2)"); 
     applet.evalCommand("s = Gerade[A, B]"); 
   }
 </script>
 <form>
   <input type="button" value="Hacer construcción" onclick="myLittelConstruction();">
 </form>

Ejemplo 4: Conviene revisar el código fuente del siguiente ejemplo de hoja dinámica que emplea JavaScript.

 http://www.geogebra.org/source/program/applet/geogebra_applet_javascript_test.htm

Ejemplo 5: Este es un ejemplo de hoja dinámica que emplea un sensor (add listener) para controlas cuándo una construcción particular se ha completado (y luego expresa "¡Bien hecho!" - en inglés Well done.).

 http://www.geogebra.org/en/examples/javascriptAutomaticCheckingExercise.html

Métodos Disponibles

Método de Firma - Signature - Desde Descripción
boolean evalCommand(String cmdString) 3.0 Evalúa la cadena dada como cuando se la ingresa desde la Barra de Entrada de GeoGebra. Da por resultado si fue exitosa la evaluación.
A partir de GeoGebra 3.2 se puede pasar múltiples comandos de a una vez separando cada uno de ellos con \n.
Nota: usar elparámetro del idioma (language) para controlar que operen correctamente los nombres de los comandos.
void setUndoPoint() 3.2 Fija un punto de deshace. Útil cuando se quiere que el usuario pueda deshacer lo que la acción de evalCommand, por ejemplo si se ha hecho un botón HTML para actuar como una herramienta de usuario

Con estos métodos se puede implementar comunicaciones Applet a JavaScript. Cuando se los emplea, es preciso asegurarse de haber insertado la opción MAYSCRIPT añadida al final de la primera línea de la etiqueta del applet (applet tag). Por eejmplo:

 <applet name="ggbApplet" code="geogebra.GeoGebraApplet" codebase="." archive="geogebra.jar" width="500" height="250" MAYSCRIPT>

La opción MAYSCRIPT sólo se requiere para comunicaciones GeoGebraApplet a JavaScript; no es necesaria para métodos de acceso de JavaScript a GeoGebraApplet.

Por ejemplo, estos métodos se pueden emplear para

Estableciendo el Estado de los Objetos

Métodos Generales


Método de Firma (Signature) Desde Descripción
void deleteObject(String objName) 2.7 Elimina el objeto del nombre dado.
void setValue(String objName, double value) 3.2 Fija el doble valor del objeto con el nombre dado. Atención: si el objeto especificado es booleano, se debe usar el valor 1 para establecerlo como verdadero y cualquier otro, para falso. Para cualquier otro tipo de objeto, no se hace nada.
void setCoords(String objName, double x, double y) 3.0 Fija las coordenadas del objeto del nombre dado. Atención: si el objeto especificado no es un punto o un vector, no se hace nada.
void setColor(String objName, int red, int green, int blue) 2.7 Fija el color del objeto con el nombre dado.
void setVisible(String objName, boolean visible) 2.7 Muestra u oculta el objeto con el nombre dado en la vista gráfica.
void setLabelVisible(String objName, boolean visible) 3.0 Muestra u oculta los rótulos del objeto con el nombre dado en la vista gráfica.
void setLabelStyle(String objName, boolean visible) 3.0 Fija el estilo del rótulo del objeto con el nombre dado en la vista gráfica. Los estilos de rótulo posibles son NOMBRE = 0, NOMBRE_VALOR = 1, VALOR = 2 y (a partir de GeoGebra 3.2) SUBTITULO = 3
void setFixed(String objName, boolean flag) 3.0 Establecer el estado fijo del objeto con el nombre dado. Atención: los objetos fijos no puede modificarse.
void setTrace(String objName, boolean flag) 3.0 Activa o desactiva el rastro del objeto con el nombre dado.
boolean renameObject(String oldObjName, String newObjName) 3.2 Cambia el nombre del objeto del previo, oldObjName al nuevo, newObjName. Indica si se ha logrado renombrarlo
void setLayer(String objName) 3.2 Fija la capa del objeto
void setLayerVisible(int layer, boolean visible) 3.2 Muestra u ocular todos los objetos en la capa dada
void setLineStyle(String objName, int style) 3.2 Fija el estilo del trazo para el objeto (0 a 4)
void setLineThickness(String objName, int thickness) 3.2 Fija el grosor del objeto (1 a 13, -1 por omisión)
void setPointStyle(String objName, int style) 3.2 Fija el estilo de los puntos (-1 por omisión, 0 redondel sombreado, 1 redondel hueco, 2 cuz, 3 signo más, 4 rombo sombreado, 5 rombo hueco, 6 triángulo (al norte), 7 triángulo (al sur), 8 triángulo (al este), 9 triángulo (al oeste))
void setPointSize(String objName, int size) 3.2 Fija el tamaño del punto (desde 1 a 9)
void setFilling(String objName, double filling) 3.2 Fija el sombreado de un objeto (desde 0 a 1)
String getPNGBase64(double exportScale, boolean transparent, double DPI) 4.0 Da por resultado la cadena de la Vista Gráfica 1 codificada en base64
eg var str = ggbApplet.getPNGBase64(1, true, 72);
boolean writePNGtoFile(String filename, double exportScale, boolean transparent, double DPI) 4.0 Exporta la Vista Gráfica 1 a un archivo .PNG (sólo para signed applets, firmadas)
eg var success = ggbApplet.writePNGtoFile("c:\\test.png", 1, false, 300);
boolean isIndependent(String objName) 4.0 Controla si el objeto del nombre dado, objName, es independiente
boolean isMoveable(String objName) 4.0 Controla si el objeto del nombre dado, objName es desplazable
String getBase64() 4.0 Da por resultado la construcción activa como un archivo .ggb codificado en base64
void setBase64(String) 4.0 Establece la construcción activa desde un archivo .ggb en código de base64

Animación Automática

Method Signature Since Description
void setAnimating(String objName, boolean animate) 3.2 Sets whether an object should be animated. This does not start the animation yet, use startAnimation() to do so.
void setAnimationSpeed(String objName, double speed) 3.2 Sets the animation speed of an object.
void startAnimation() 3.2 Starts automatic animation for all objects with the animating flag set, see setAnimating()
void stopAnimation() 3.2 Stops animation for all objects with the animating flag set, see setAnimating()
boolean isAnimationRunning() 3.2 Returns whether automatic animation is currently running.

Sobre el Estado de los Objetos

Method Signature Since Description
double getXcoord(String objName) 2.7 Returns the cartesian x-coord of the object with the given name. Note: returns 0 if the object is not a point or a vector.
double getYcoord(String objName) 2.7 Returns the cartesian y-coord of the object with the given name. Note: returns 0 if the object is not a point or a vector.
double getValue(String objName) 3.2 Returns the double value of the object with the given name (e.g. length of segment, area of polygon). Note: returns 1 for a boolean object with value true. Otherwise 0 is returned.
String getColor(String objName) 2.7 Returns the color of the object with the given name as a hex string, e.g. "#FF0000" for red. Note that the hex string always starts with # and contains no lower case letters.
boolean getVisible(String objName) 3.2 Returns true or false depending on whether the object is visible in the Graphics View. Returns false if the object does not exist.
String getValueString(String objName) 2.7 Returns the value of the object with the given name as a string.
String getDefinitionString(String objName) 2.7 Returns the definition of the object with the given name as a string.
String getCommandString(String objName) 2.7 Returns the command of the object with the given name as a string.
String getObjectType(String objName) 2.7 Returns the type of the given object as a string (like "point", "line", "circle", etc.).
boolean exists(String objName) 2.7 Returns whether an object with the given name exists in the construction.
boolean isDefined(String objName) 2.7 Returns whether the given object's value is valid at the moment.
String [] getAllObjectNames()
Deprecated since 3.0
2.7 Returns an array with all object names in the construction. Note: using arrays in JavaScript causes problems with some browsers. Use getObjectNumber() and getObjectName() instead.
int getObjectNumber() 3.0 Returns the number of objects in the construction.
String getObjectName(int i) 3.0 Returns the name of the n-th object of the construction.
String getLayer(String objName) 3.2 Returns the layer of the object.
int getLineStyle(String objName) 3.2 Gets the line style for the object (0 to 4)
int getLineThickness(String objName) 3.2 Gets the thickness of the line (1 to 13)
int getPointStyle(String objName) 3.2 Gets the style of points (-1 default, 0 filled circle, 1 circle, 2 cross, 3 plus, 4 filled diamond, 5 unfilled diamond, 6 triangle (north), 7 triangle (south), 8 triangle (east), 9 triangle (west))
int getPointSize(String objName) 3.2 Gets the size of a point (from 1 to 9)
double getFilling(String objName) 3.2 Gets the filling of an object (from 0 to 1)

Construcción / Interfaz de Uso

Method Signature Since Description
void setMode(int mode) 2.7 Sets the mouse mode (i.e. tool) for the graphics window (ver [en:Reference:Toolbar|Referencia de Barra de Herramientas] y los parámetros applet "showToolBar" y  "customToolBar" )
void openFile(String strURL) 2.7 Opens a construction from a  file (given as absolute or relative URL string)
void reset() 2.7 Reloads the initial construction (given in filename parameter) of this applet.
void refreshViews() 2.7 Refreshs all views. Note: this clears all traces in the graphics window.
void setOnTheFlyPointCreationActive(boolean flag)
3.2 Turns on the fly creation of points in graphics view on (true) or off (false). Note: this is useful if you don't want tools to have the side effect of creating points. For example, when this flag is set to false, the tool "line through two points" will not create points on the fly when you click on the background of the graphics view.
void hideCursorWhenDragging(boolean flag)
3.2 Hides (true) or shows (false) the mouse cursor (pointer) when dragging an object to change the construction.
void setRepaintingActive(boolean flag)
2.7 Turns the repainting of this applet on (true) or off (false). Note: use this method for efficient repainting when you invoke several methods.
void setErrorDialogsActive(boolean flag) 3.0 Turns showing of error dialogs on (true) or off (false). Note: this is especially useful together with evalCommand().
void setCoordSystem(double xmin, double xmax, double ymin, double ymax) 3.0 Sets the Cartesian coordinate system of the graphics window.
void setAxesVisible(boolean xAxis, boolean yAxis) 3.0 Shows or hides the x- and y-axis of the coordinate system in the graphics window.
void setGridVisible(boolean flag) 3.0 Shows or hides the coordinate grid in the graphics window.

Comunicación entre JavaScript y GeoGebraApplet

Los siguientes métodos permiten implementar un Applet para la comunicación JavaScript. Al emplearlos, es preciso asegurarse de insertar la opción MAYSCRIPT añadida al final de la primera línea de la etiqueta del applet en curso (applet tag). Por ejemplo:

<applet name="ggbApplet" code="geogebra.GeoGebraApplet" codebase="." archive="geogebra.jar" width="500" height="250" MAYSCRIPT>. La opción MAYSCRIPT se precisa únicamente para comunicación GeoGebraApplet a JavaScript; no es necesaria para el acceso de JavaScript a los métodos de GeoGebraApplet. Por ejemplo, estos métodos pueden emplearse para:

Method Signature Since Description
void registerAddListener(String JSFunctionName) 3.0 Registers a JavaScript function as an add listener for the applet's construction. Whenever a new object is created in the GeoGebraApplet's construction, the JavaScript function JSFunctionName is called using the name of the newly created object as its single argument.

Example: First, register a listening JavaScript function:

ggbApplet.registerAddListener("myAddListenerFunction");

When an object "A" is created, the GeoGebra Applet will call the Javascript function

myAddListenerFunction("A");
void unregisterAddListener(String objName) 3.0 Removes a previously registered add listener, see registerAddListener()
void registerRemoveListener(String JSFunctionName) 3.0 Registers a JavaScript function as a remove listener for the applet's construction. Whenever an object is deleted from the GeoGebraApplet's construction, the JavaScript function JSFunctionName is called using the name of the deleted object as its single argument. Note: when a construction is cleared, remove is not called for every single object, see registerClearListener().

Example: First, register a listening JavaScript function:

ggbApplet.registerRemoveListener("myRemoveListenerFunction");

When the object "A" is deleted, the GeoGebra Applet will call the Javascript function

myRemoveListenerFunction("A");
void unregisterRemoveListener(String objName) 3.0 Removes a previously registered remove listener, see registerRemoveListener()
void registerUpdateListener(String JSFunctionName) 3.0 Registers a JavaScript function as a update listener for the applet's construction. Whenever any object is updated in the GeoGebraApplet's construction, the JavaScript function JSFunctionNameis called using the name of the updated object as its single argument. Note: when you only want to listen for the updates of a single object use registerObjectUpdateListener() instead.

Example: First, register a listening JavaScript function:

ggbApplet.registerUpdateListener("myUpdateListenerFunction");

When the object "A" is updated, the GeoGebra Applet will call the Javascript function

myUpdateListenerFunction("A");
void unregisterUpdateListener(String objName) 3.0 Removes a previously registered update listener, see registerUpdateListener()
void registerObjectUpdateListener(String objName, String JSFunctionName) 3.0 Registers a JavaScript function as an update listener for a single object. Whenever the object with the given name is updated, the JavaScript function JSFunctionNameis called using the name of the updated object as its single argument. If objName previously had a mapping JavaScript function, the old value is replaced. Note: all object updated listeners are unregistered when their object is removed or the construction is cleared, see registerRemoveListener() and registerClearListener().

Example: First, register a listening JavaScript function:

ggbApplet.registerObjectUpdateListener("A", "myAupdateListenerFunction");

Whenever the object A is updated, the GeoGebra Applet will call the Javascript function

myAupdateListenerFunction("A");

Note: an object update listener will still work after an object is renamed.

void unregisterObjectUpdateListener(String objName) 3.0 Removes a previously registered object update listener of the object with the given name, see registerObjectUpdateListener()
void registerRenameListener(String JSFunctionName) 3.0 Registers a JavaScript function as a rename listener for the applet's construction. Whenever an object is renamed in the GeoGebraApplet's construction, the JavaScript function JSFunctionName is called using the old name and the new name of the renamed object as its two arguments.

Example: First, register a listening JavaScript function:

ggbApplet.registerRenameListener("myRenameListenerFunction");

When an object "A" is renamed to "B", the GeoGebra Applet will call the Javascript function

myRenameListenerFunction("A", "B");
void unregisterRenameListener(String objName) 3.0 Removes a previously registered rename listener, see registerRenameListener()
void registerClearListener(String JSFunctionName) 3.0 Registers a JavaScript function as a clear listener for the applet's construction. Whenever the construction in the GeoGebraApplet is cleared (i.e. all objects are removed), the JavaScript function JSFunctionName is called using no arguments. Note: all update listeners are unregistered when a construction is cleared. See registerUpdateListener() and registerRemoveListener().

Example: First, register a listening JavaScript function:

ggbApplet.registerClearListener("myClearListenerFunction");

When the construction is cleared (i.e. after reseting a construction or opening a new construction file), the GeoGebra Applet will call the Javascript function

myClearListenerFunction();
void unregisterClearListener(String JSFunctionName) 3.0 Removes a previously registered clear listener, see registerClearListener()

Formato XML de GeoGebra

Con estos métodos se puede establecer prácticamente todo en una construcción (ver Referencia XML ).

Method Signature Since Description
void evalXML(String xmlString) 2.7 Evaluates the given XML string and changes the current construction. Note: the construction is NOT cleared before evaluating the XML string.
void setXML(String xmlString) 2.7 Evaluates the given XML string and changes the current construction. Note: the construction is cleared before evaluating the XML string. This method could be used to load constructions.
String getXML()
2.7 Returns the current construction in GeoGebra's XML format. This method could be used to save constructions.
String getXML(String objName)
3.2 Returns the GeoGebra XML string for the given object, i.e. only the <element> tag is returned.
String getAlgorithmXML(String objName)
3.2 For a dependent GeoElement objName the XML string of the parent algorithm and all its output objects is returned. For a free GeoElement objName "" is returned.

Misceláneas

Método de Firma (Signature) Desde Descripción
String evalMathPiper(String string) 3.2 Pasa la cadena a MathPiper y establece el resultado como una Cadena.

Eliminado en GeoGebra 4.0 y será reemplazado con evalGeoGebraCAS() wn GeoGebra 4.2

String getIPAddress() 3.2 Da por resultado la dirección de IP de la computadora local como una Cadena; por ejemplo, "192.168.0.4"
String getHostname() 3.2 Da por resultado el nombre del host de la computadora local como una Cadena
void debug(String string) 3.2 Imprime la cadena de la Consola Java

en:Reference:JavaScript fr:Référence:JavaScript it:Riferimenti:JavaScript

© 2024 International GeoGebra Institute