IdentifiantMot de passe
Loading...
Mot de passe oubli� ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les r�ponses en temps r�el, voter pour les messages, poser vos propres questions et recevoir la newsletter

JavaScript Discussion :

Comment appeler une fonction SVG


Sujet :

JavaScript

  1. #1
    Membre confirm�
    Inscrit en
    Janvier 2009
    Messages
    163
    D�tails du profil
    Informations forums :
    Inscription : Janvier 2009
    Messages : 163
    Par d�faut Comment appeler une fonction SVG
    Bonjour � toutes et � tous,

    J'y ai trouv� des �l�ments de r�ponse http://www.developpez.net/forums/d75...svg-code-page/

    J'ai pris l'exemple ci-dessous dans les sources fournis comme exemple de l'ouvrage JAVASCRIPT la R�f�rence O'REILLY par David Flanagan.
    Malheureusement je ne trouve pas d'exemple de l'utilisation de cette fonction.
    C'est surtout l'aspect HTML (ou placer le graphique, comment le d�clarer) et un peu le Javascript d'appel dont j'ai besoin.
    Merci de votre aide.

    Code : S�lectionner tout - Visualiser dans une fen�tre � part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    /**
     * Draw a pie chart into an <svg> element.
     * Arguments:
     *   canvas: the SVG element (or the id of that element) to draw into.
     *   data: an array of numbers to chart, one for each wedge of the pie.
     *   cx, cy, r: the center and radius of the pie
     *   colors: an array of HTML color strings, one for each wedge
     *   labels: an array of labels to appear in the legend, one for each wedge
     *   lx, ly: the upper-left corner of the chart legend
     */
    function pieChart(canvas, data, cx, cy, r, colors, labels, lx, ly) {
        // Locate canvas if specified by id instead of element
        if (typeof canvas == "string") canvas = document.getElementById(canvas);
     
        // Add up the data values so we know how big the pie is
        var total = 0;
        for(var i = 0; i < data.length; i++) total += data[i];
     
        // Now figure out how big each slice of pie is.  Angles in radians.
        var angles = []
        for(var i = 0; i < data.length; i++) angles[i] = data[i]/total*Math.PI*2;
     
        // Loop through each slice of pie.
        startangle = 0;
        for(var i = 0; i < data.length; i++) {
            // This is where the wedge ends
            var endangle = startangle + angles[i];
     
            // Compute the two points where our wedge intersects the circle
            // These formulas are chosen so that an angle of 0 is at 12 o'clock
            // and positive angles increase clockwise.
            var x1 = cx + r * Math.sin(startangle);
            var y1 = cy - r * Math.cos(startangle);
            var x2 = cx + r * Math.sin(endangle);
            var y2 = cy - r * Math.cos(endangle);
     
            // This is a flag for angles larger than than a half circle
            var big = 0;
            if (endangle - startangle > Math.PI) big = 1;
     
            // We describe a wedge with an <svg:path> element
            // Notice that we create this with createElementNS()
            var path = document.createElementNS(SVG.ns, "path");
     
            // This string holds the path details
            var d = "M " + cx + "," + cy +  // Start at circle center
                " L " + x1 + "," + y1 +     // Draw line to (x1,y1)
                " A " + r + "," + r +       // Draw an arc of radius r
                " 0 " + big + " 1 " +       // Arc details...
                x2 + "," + y2 +             // Arc goes to to (x2,y2)
                " Z";                       // Close path back to (cx,cy)
            // This is an XML element, so all attributes must be set
            // with setAttribute().  We can't just use JavaScript properties
            path.setAttribute("d", d);              // Set this path 
            path.setAttribute("fill", colors[i]);   // Set wedge color
            path.setAttribute("stroke", "black");   // Outline wedge in black
            path.setAttribute("stroke-width", "2"); // 2 units thick
            canvas.appendChild(path);               // Add wedge to canvas
     
            // The next wedge begins where this one ends
            startangle = endangle;
     
            // Now draw a little matching square for the key
            var icon = document.createElementNS(SVG.ns, "rect");
            icon.setAttribute("x", lx);             // Position the square
            icon.setAttribute("y", ly + 30*i);
            icon.setAttribute("width", 20);         // Size the square
            icon.setAttribute("height", 20);
            icon.setAttribute("fill", colors[i]);   // Same fill color as wedge
            icon.setAttribute("stroke", "black");   // Same outline, too.
            icon.setAttribute("stroke-width", "2");
            canvas.appendChild(icon);               // Add to the canvas
     
            // And add a label to the right of the rectangle
            var label = document.createElementNS(SVG.ns, "text");
            label.setAttribute("x", lx + 30);       // Position the text
            label.setAttribute("y", ly + 30*i + 18);
            // Text style attributes could also be set via CSS
            label.setAttribute("font-family", "sans-serif");
            label.setAttribute("font-size", "16");
            // Add a DOM text node to the <svg:text> element
            label.appendChild(document.createTextNode(labels[i]));
            canvas.appendChild(label);              // Add text to the canvas
        }
    }

  2. #2
    Membre confirm�
    Profil pro
    Inscrit en
    D�cembre 2008
    Messages
    123
    D�tails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : D�cembre 2008
    Messages : 123
    Par d�faut
    C'est la premi�re fois que je travaille avec du SVG mais voil� ce que �a me donne :

    Le code � placer dans un fichier .html :
    Code : S�lectionner tout - Visualiser dans une fen�tre � part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    <?xml version="1.0" encoding="ISO-8859-1" ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" >
    <html xmlns="http://www.w3.org/1999/xhtml" xmlns:svg="http://www.w3.org/2000/svg">
    <head>
    	<title>Test SVG</title>
    	<script type="text/javascript" src="gestion-svg.js"></script>
    </head>
    <body>
    	<h1>Titre de la page</h1>
     
    	<p>Paragraphe 1</p>
     
    	<div id="conteneur">L'élément ici présent sera remplacé par un SVG seulement si une version récente de javascript est activée et que les fichiers SVG sont pris en charge par le navigateur.</div>
     
    	<p>Paragraphe 2</p>
    </body>
    </html>

    Le code javascript, � placer dans un fichier nomm� � gestion-svg.js � :
    Code : S�lectionner tout - Visualiser dans une fen�tre � part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    /**
     * Draw a pie chart into an <svg> element.
     * [Tiré de JAVASCRIPT la Référence O'REILLY par David Flanagan]
     * Arguments:
     *   oSvg: the SVG element (or the id of that element) to draw into.
     *   data: an array of numbers to chart, one for each wedge of the pie.
     *   cx, cy, r: the center and radius of the pie
     *   colors: an array of HTML color strings, one for each wedge
     *   labels: an array of labels to appear in the legend, one for each wedge
     *   lx, ly: the upper-left corner of the chart legend
     */
    function pieChart(canvas, data, cx, cy, r, colors, labels, lx, ly) {
        // Locate canvas if specified by id instead of element
        if (typeof canvas == "string") canvas = document.getElementById(canvas);
     
        // Add up the data values so we know how big the pie is
        var total = 0;
        for(var i = 0; i < data.length; i++) total += data[i];
     
        // Now figure out how big each slice of pie is.  Angles in radians.
        var angles = []
        for(var i = 0; i < data.length; i++) angles[i] = data[i]/total*Math.PI*2;
     
        // Loop through each slice of pie.
        startangle = 0;
        for(var i = 0; i < data.length; i++) {
            // This is where the wedge ends
            var endangle = startangle + angles[i];
     
            // Compute the two points where our wedge intersects the circle
            // These formulas are chosen so that an angle of 0 is at 12 o'clock
            // and positive angles increase clockwise.
            var x1 = cx + r * Math.sin(startangle);
            var y1 = cy - r * Math.cos(startangle);
            var x2 = cx + r * Math.sin(endangle);
            var y2 = cy - r * Math.cos(endangle);
     
            // This is a flag for angles larger than than a half circle
            var big = 0;
            if (endangle - startangle > Math.PI) big = 1;
     
            // We describe a wedge with an <svg:path> element
            // Notice that we create this with createElementNS()
            var path = document.createElementNS(canvas.namespaceURI, "path");
     
            // This string holds the path details
            var d = "M " + cx + "," + cy +  // Start at circle center
                " L " + x1 + "," + y1 +     // Draw line to (x1,y1)
                " A " + r + "," + r +       // Draw an arc of radius r
                " 0 " + big + " 1 " +       // Arc details...
                x2 + "," + y2 +             // Arc goes to to (x2,y2)
                " Z";                       // Close path back to (cx,cy)
            // This is an XML element, so all attributes must be set
            // with setAttribute().  We can't just use JavaScript properties
            path.setAttribute("d", d);              // Set this path 
            path.setAttribute("fill", colors[i]);   // Set wedge color
            path.setAttribute("stroke", "black");   // Outline wedge in black
            path.setAttribute("stroke-width", "2"); // 2 units thick
            canvas.appendChild(path);               // Add wedge to canvas
     
            // The next wedge begins where this one ends
            startangle = endangle;
     
            // Now draw a little matching square for the key
            var icon = document.createElementNS(canvas.namespaceURI, "rect");
            icon.setAttribute("x", lx);             // Position the square
            icon.setAttribute("y", ly + 30*i);
            icon.setAttribute("width", 20);         // Size the square
            icon.setAttribute("height", 20);
            icon.setAttribute("fill", colors[i]);   // Same fill color as wedge
            icon.setAttribute("stroke", "black");   // Same outline, too.
            icon.setAttribute("stroke-width", "2");
            canvas.appendChild(icon);               // Add to the canvas
     
            // And add a label to the right of the rectangle
            var label = document.createElementNS(canvas.namespaceURI, "text");
            label.setAttribute("x", lx + 30);       // Position the text
            label.setAttribute("y", ly + 30*i + 18);
            // Text style attributes could also be set via CSS
            label.setAttribute("font-family", "sans-serif");
            label.setAttribute("font-size", "16");
            // Add a DOM text node to the <svg:text> element
            label.appendChild(document.createTextNode(labels[i]));
            canvas.appendChild(label);              // Add text to the canvas
        }
    }
     
    /**
     * Crée un élément <svg> conforme et remplace un élément de la page avec lui.
     * [Par grafik.muzik à gmail point com, 20 juin 2009]
     *
     * param    sIdSubstitut  Identifiant (string) de l'élément à remplacer
     * param    iLargeur      Largeur en pixel (integer) du SVG
     * param    iHauteur      Hauteur en pixel (integer) du SVG
     * return                 Élément SVG (object) ajouté dans la page
     */
    function creerSvgVide(sIdSubstitut, iLargeur, iHauteur) {
        //Récupère le noeud élément (c'est-à-dire la référence vers la balise XHTML) qui sera remplacé par l'élément SVG
        var oSubstitut = document.getElementById(sIdSubstitut);
     
        //Créé un élément SVG avec une largeur et une hauteur
        var oSvg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
        oSvg.setAttribute("version", "1.1");
        oSvg.setAttribute("width", iLargeur);
        oSvg.setAttribute("height", iHauteur);
     
        //Place l'élément SVG dans la page XHTML à la place de l'élément substitut
        oSubstitut.parentNode.replaceChild(oSvg, oSubstitut);
     
        //Retourne la référence du SVG, afin de s'en servir avec l'autre fonction
        return oSvg;
    }
     
    //Ne déclenche les fonctions javascript qu'une fois la page chargée complètement
    window.addEventListener("load", function() {
        //Créer le canvas SVG
        var sIdSubstitut = 'conteneur'; //Nom (en fait ID) de l'élément à remplacer par le SVG (le « canvas »)
        var iLargeur = '400'; //Largeur du SVG
        var iHauteur = '300'; //Hauteur du SVG
        var oSvg = creerSvgVide(sIdSubstitut, iLargeur, iHauteur); //Fonction qui crée un SVG
     
        //Afficher un graphique en pointe de tarte dans le SVG
        var data = [30, 35, 15]; //Les portions de chaque pointe de tarte
        var colors = ['#369', '#c66', '#9c6']; //Les couleurs de chaque pointe (à 3 ou 6 caractères)
        var labels = ['Bleu', 'Rouge', 'Vert']; //Le texte des étiquettes associées aux pointes
        var cx = iLargeur/2; //Équivaut à 200, centre le graphique horizontalement
        var cy = iHauteur/2; //Équivaut à 150, centre le graphique verticalement
        var r = 90; //Rayon du graphique
        var lx = 15; //position des étiquettes, à partir de la gauche (abscisse x)
        var ly = 20; //position des étiquettes, à partir du haut (ordonnée y)
        pieChart(oSvg, data, cx, cy, r, colors, labels, lx, ly); //Fonction qui ajoute une pointe de tarte dans le SVG
    }, false);
    Le code fourni comportait une erreur, il faisait appel � une variable globale non d�clar�e, j'ai modifi� le script pour qu'il fonctionne. J'ai test� et �a fonctionne sous Firefox 3, Google Chrome 1 et Opera 9. Bien s�r, �a ne fonctionne pas sur Internet Explorer.

    En gros, j'ai cr�� une page HTML de base qui contient un �l�ment division (DIV) et deux �l�ments paragraphes (P). La page appelle le javascript � l'aide de la ligne � <script type="text/javascript" src="gestion-svg.js"></script> �. Un fois la page charg�e, les fonctions se d�clenchent et modifient la page. La premi�re fonction Javascript que j'ai cr�� (en m'inspirant du d�but de solution que tu as donn�) cr�e une image SVG vide et remplace l'�l�ment div de la page avec ce SVG. Ensuite, la fonction tir�e de ton ouvrage est appel�e. Cette fonction ins�re des �l�ments de dessin (une pointe de tarte) dans le SVG.

    En somme, cette page utilise 4 � technologies �: le XHTML, le DOM, le Javascript et le SVG.

    J'esp�re que �a t'aide! Perso je n'ai jamais pass� autant de temps sur un post donc tu est chanceux

  3. #3
    Membre confirm�
    Inscrit en
    Janvier 2009
    Messages
    163
    D�tails du profil
    Informations forums :
    Inscription : Janvier 2009
    Messages : 163
    Par d�faut Un grand merci � grafik.muzik
    En effet, quelle r�ponse compl�te et d�taill�e !
    Je ne peux pas la mettre en �uvre tout de suite car mon ordinateur est chez le r�parateur ! Je ne manquerai pas d'en faire un rapport.
    Encore merci !

  4. #4
    Membre confirm�
    Profil pro
    Inscrit en
    D�cembre 2008
    Messages
    123
    D�tails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : D�cembre 2008
    Messages : 123
    Par d�faut
    Tout le plaisir est pour moi

+ R�pondre � la discussion
Cette discussion est r�solue.

Discussions similaires

  1. Comment appeller une fonction dynamiquement, à partir d'un argument
    Par Invit� dans le forum G�n�ral JavaScript
    R�ponses: 4
    Dernier message: 23/04/2006, 16h47
  2. R�ponses: 2
    Dernier message: 13/03/2006, 13h54
  3. comment appeler une fonction JAVA en JAVASCRIPT ?
    Par heleneh dans le forum Servlets/JSP
    R�ponses: 2
    Dernier message: 13/09/2005, 12h21
  4. comment appeler une fonction JAVA en JAVASCRIPT ?
    Par heleneh dans le forum G�n�ral JavaScript
    R�ponses: 1
    Dernier message: 13/09/2005, 12h04
  5. Comment appeler une fonction JavaScript depuis Delphi ?
    Par Alfred12 dans le forum Web & r�seau
    R�ponses: 4
    Dernier message: 17/06/2005, 18h15

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo