Référence:JavaScript

De GeoGebra Manual
Aller à : navigation, rechercher

EN TRAVAUX !!! --Noel Lambert 10 décembre 2011 à 19:35 (CET)


Description des méthodes publiques utilisables dans geogebra.GeoGebraApplet à l’aide de JavaScript par l’intermédiaire d’une page HTML.


Exemples

Exemple 1 : le fragment de code HTML suivant ajoute un bouton "Réinitialiser" dans une page HTML, ce qui permet à l’utilisateur de ramener la construction affichée par GeoGebra dans son état initial : <form> <input type="button" value="Réinitialiser" onclick="document.applets[0].reset();"> </form>


Exemple 2 : celui-ci ajoute deux boutons "Cacher A" et " Afficher A" pour changer l’état d’affichage de l’objet nommé “A" dans la construction <form> <input type="button" value="Cacher A" onclick="document.applets[0].setVisible('A', false);"> <input type="button" value="Afficher A" onclick="document.applets[0].setVisible('A', true);"> </form>


Exemple 3: Une fonction JavaScript "maConstruction()" est utilisée pour appeler plusieurs méthodes de l’appliquette GeoGebra. Note : La langue est fixée à Français ("fr") avec le paramètre "language" dans la balise de l’appliquette afin de faire en sorte que la commande française "Droite" fonctionne. <applet name="ggbApplet" code="geogebra.GeoGebraApplet"

       archive="geogebra.jar" 
       width=200 height=40>
   <param name ="fileNom" value="circle.ggb">
   <param name ="framePossible" value="false">
   <param name ="language" value="fr">
    <a href="http://www.java.com"> Installez  Java 1.4.2</a> (ou supérieure) pour utiliser cette  page.

</applet> <script type="text/javascript"> function maConstruction() { var applet = document.ggbApplet; applet.evalCommand("A = (1,1)"); applet.evalCommand("B = (3,2)"); applet.evalCommand("s = Droite[A, B]"); } </script> <form> <input type="button" value="Faire la construction" onclick="maConstruction();"> </form>


Exemple 4: Have a look at the source code of the following example worksheet that uses JavaScript.

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

Exemple 5: This is an example worksheet that uses an add listener to check when a particular construction has been completed (and then says "Well done").

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

Méthodes utilisables

Méthode Description
evalCommand(commande) Évalue la chaîne comme si vous l’aviez entrée dans le champ de saisie [ex : evalCommand('s = Droite[A, B]')].
Vous pouvez utiliser plusieurs commandes en les séparant par "\n"
Note : Utilisez le paramètre “language” language parameter pour vous assurez que la commande de votre langue est reconnue.
void setUndoPoint() Sets an undo point. Useful if you want the user to be able to undo that action of evalCommand eg if you have made an HTML button to act as a custom tool

With these methods you can implement Applet to JavaScript communication. When you use any of the following methods, you should make sure to insert the MAYSCRIPT option add the end of the first line of your applet tag. For example:

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

The MAYSCRIPT option is only needed for GeoGebraApplet to JavaScript communication; it is not needed for JavaScript to access the GeoGebraApplet methods.

For example, these methods can be used to

Définir l’état d’un objet

General methods

Méthode Description
deleteObject(nom) Efface l’objet cité.[ex : deleteObject('A')].
setValue(nom, valeur) Affecte la valeur à l’objet cité [ex : setValue('n',36)]. Note : Si cet objet n’est pas un nombre, rien ne se passe. Si l’objet est un booléen, utiliser la valeur 1 pour le mettre à ‘Vrai’, n’importe quelle valeur pour le mettre à ‘Faux’.
setCoords(nom, x, y) Affecte les coordonnées à l’objet [ex : setCoords('A',-1,3)]. Note : Si cet objet n’est ni point ni vecteur, rien ne se passe.
setColor(nom, rouge, vert, bleu) Affecte la couleur RVB à l’objet [ setColor('A',200,100,100)].
setVisible(nom, booléen) Affiche (true) ou Cache (false) l’objet cité dans la vue Graphique [ex : setVisible('A',true)].
setLabelVisible(nom, booléen) Affiche (true) ou Cache (false) l’étiquette de l’objet cité dans la vue Graphique [ex : setLabelVisible('A',false)].
setLabelStyle(nom, booléen) Définit le style de l’étiquette de l’objet cité dans Graphique. Nom = 0, Nom & Valeur = 1, Valeur = 2 et Légende=3. [ex : setLabelStyle('A',1)],
setFixed(nom, booléen) Définit la liberté de l’objet cité [ex : setFixed('A',true)].
Note : Les objets fixes ne peuvent être modifiés.
setTrace(nom, booléen) Active ou non la trace de l’objet cité [ex : setTrace('A',false)].
renameObject(ancien nom, nouveau nom) 3.2 Renomme l’objet ancien nom en l’objet nouveau nom
setLayer(nom) Définit le calque de l’objet cité.
setLayerVisible(n°, booléen) Affiche ou cache tous les objets du calque n°
setLineStyle(nom,entier) Définit le style du trait (de 0 à 4)
setLineThickness(nom,entier) Définit l’épaisseur de l’objet (de 1 à 13) (1 par défaut)
setPointStyle(nom,entier) Définit le style du point (-1 par défaut, 0 disque, 1 cercle, 2 croix,3 plus, 4 diamant plein, 5 diamant vide, 6 triangle (nord), 7 triangle (sud), 8 triangle (est), 9 triangle (ouest))
setPointSize(nom,entier) Définit la taille du point (de 1 à 9)
setFilling(nom,nombre) Définit le remplissage de l’objet (de 0 à 1)

Animation automatique

Méthode Description
setAnimating(nom, booléen) Définit si l’objet cité peut être animé. Cela ne lance pas l'animation, utilisez startAnimation() pour le faire.
setAnimationSpeed(nom, nombre) Définit la vitesse d’animation de l’objet cité.
startAnimation() Lance l’animation pour les objets pouvant être animés.
stopAnimation() Arrête l’animation en cours.
isAnimationRunning() Retourne un booléen précisant si une animation est en cours ou non.

Connaître l’état d’un objet

Méthode Description
getXcoord(nom) Retourne l’abscisse de l’objet cité [ex : getXcoord('A')]. Note : Retourne 0 si l’objet n’est ni un point ni un vecteur.
getYcoord(nom) Retourne l’ordonnée de l’objet cité [ex : getYcoord('u')]. Note : Retourne 0 si l’objet n’est ni un point ni un vecteur.
getValue(nom) Retourne la valeur de l’objet cité ( longueur pour un segment, aire pour un polygone, etc.) [ex : getValue('poly1')]. Note : Retourne 0 s’il l’objet n’a pas de valeur associée. Si l’objet est un booléen, retourne 1 pour ‘Vrai’, 0 pour ‘Faux’.
getColor(nom) Retourne la couleur de l’objet cité sous forme d’une chaîne hexadécimale, par ex. : "#FF0000" pour rouge. Note la chaîne hexadécimale commence toujours par # et ne contient pas de lettres minuscules.
getVisible(nom) Retourne ‘true’ ou ‘false’ suivant que l’objet cité est affiché ou non dans la vue Graphique. Retourne ‘false’ si l'objet n'existe pas.
getValueString(nom) Retourne la valeur de l’objet cité sous forme de chaîne.
getDefinitionString(nom) Retourne la définition (l’info bulle) de l’objet cité.
getCommandString(nom) Retourne la commande à saisir pour créer l’objet cité.
getObjectType(nom) Retourne le type de l’objet cité sous forme de chaîne (comme "point", "line", "circle", etc. en Anglais !).
exists(nom) Retourne un booléen attestant l’existence ou non de l’objet cité dans la construction.
isDefined(nom) Retourne un booléen attestant la validité actuelle ou non de l’objet .
getObjectNumber() Retourne le nombre d’objets dans la construction.
getObjectName(n) Retourne le nom du n-ème objet de la construction (attention, le compteur commence à 0).
getLayer(nom) Retourne le numéro du calque de l’objet cité.
getLineStyle(nom) Retourne le style du trait (de 0 à 4)
getLineThickness(nom) Retourne l’épaisseur de l’objet (de 1 à 13) (1 par défaut)
getPointStyle(nom) Retourne le style du point (-1 par défaut, 0 disque, 1 cercle, 2 croix,3 plus, 4 diamant plein, 5 diamant vide, 6 triangle (nord), 7 triangle (sud), 8 triangle (est), 9 triangle (ouest))
getPointSize(nom) Retourne la taille du point (de 1 à 9)
getFilling(nom) Retourne le remplissage de l’objet (de 0 à 1)

Construction / Interface Utilisateur

Méthode Description
setMode(code du mode) Définit le mode au code fourni

[ex : setMode(0), pour mode Déplacer].

(voir toolbar reference et applet parameters "showToolBar" and  "customToolBar" )
openFile(URL) Ouvre le fichier dont l’URL est donnée sous forme absolue ou relative)[ex : openFile('fichier.ggb')].
reset() Réinitialise la construction.
refreshViews() Rafraîchit l’affichage. Note : cela efface toutes les traces dans la vue Graphique.
setOnTheFlyPointCreationActive(booléen)
Autorise (true) ou non (false) la création de points "à la volée". Note: A utiliser si vous ne désirez pas que les outils créent des points.
hideCursorWhenDragging(booléen)
Affiche(true) ou non (false) le curseur de la souris quand on déplace un object.
setRepaintingActive(booléen)
Active (true) ou non (false) le recalcul de la figure). Note : cette méthode est surtout à utiliser quand vous utilisez plusieurs méthodes.
setErrorDialogsActive(boolean flag) Bascule pour l’affichage ou non du dialogue d’erreur. Note: c'est très utile avec l'utilisation de evalCommand().
setCoordSystem(xmin, xmax,ymin,ymax) Définit la fenêtre graphique

[ex : setCoordSystem(-5,10,-1,20)].

setAxesVisible(booléen, booléen) Affiche (true) ou Cache (true) indépendamment chacun des axes [ex : setAxesVisible(true, false)].
setGridVisible(booléen) Affiche (true) ou Cache (true) la grille.

Communication de GeoGebraApplet à JavaScript

Avec ces méthodes vous pouvez implémenter une communication de l’appliquette au JavaScript. Quand vous utilisez une des méthodes suivantes, vous devez vous assurer que vous avez inséré l’option MAYSCRIPT à la fin de la ligne d’appel de l’appliquette.

Par exemple :

<applet name="ggbApplet" code="geogebra.GeoGebraApplet" codebase="." archive="geogebra.jar" width="500" height="250" MAYSCRIPT>. L'option MAYSCRIPT n'est seulement nécessaire que pour la communication de GeoGebraAppletavec JavaScript ; ellen'est pas nécessaire à JavaScript pour accéder au méhtodes de GeoGebraApplet. Par exemple, ces méthodes peuvent être utilisées pour :

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

GeoGebra's XML format

With these methods you can set everything in a construction (see XML Reference ).

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.

Miscellaneous

Method Signature Since Description
String evalMathPiper(String string) 3.2 Passes the string to MathPiper and returns the result as a String.
String getIPAddress() 3.2 Returns the IP address of the local computer as a String eg "192.168.0.4"
String getHostname() 3.2 Returns the hostname of the local computer as a String
void debug(String string) 3.2 Prints the string to the Java Console
© 2024 International GeoGebra Institute