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 :

[SVG] Adapter la viewBox à son contenu


Sujet :

JavaScript

  1. #1
    Membre du Club
    Homme Profil pro
    Technicien maintenance
    Inscrit en
    Août 2016
    Messages
    76
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Marne (Champagne Ardenne)

    Informations professionnelles :
    Activité : Technicien maintenance

    Informations forums :
    Inscription : Août 2016
    Messages : 76
    Points : 67
    Points
    67
    Par défaut [SVG] Adapter la viewBox à son contenu
    Bonjour,
    Pouvez vous me dire si il existent une fonction permettant d'adapté le viewBox a sont contenu?
    Dans l'exemple suivant: la rotation du chemin est prévu en paramétrage, le but serai de minimisé la zone rouge quel que soit l'angle paramétré.
    Code html : 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
    <!DOCTYPE html>
    <html lang="">
      <head>
        <meta charset="utf-8">
        <title></title>
      </head>
      <body>
        <header></header>
        <main>
    		<table border="10px">
    			<tr height="50px">
    							<td>
    							width:<input id="slide_width" type="range" value="100" min="100" max="300"/>
    							</td>
    			</tr>
    							<td>
    							padding:<input id="slide_padding" type="range" value="0" min="0" max="100"/>
    							</td>
    			<tr>
    				<td>
    					<table>
    						<tr>
    							<td>
    							<label for="cons">Gauge Consigne</label>
    							</td>
    						</tr>
    						<tr>
    							<td>
    							<input id="cons" type="number" value="0" min="0" max="360"/>
    							</td>
    						</tr>
    						<tr>
    							<td>
    							<input id="slide" type="range" value="0" min="0" max="360"/>
    							</td>
    						</tr>
    					</table>
    				</td>
    				<td id="gauge_svg" width=100px height=200px style="background:lime;">
    			</tr>
    		</table>
    <style>
     
    </style>
    <script>
    class gauge {
            constructor({id = "gauge_svg"}){
                    this.id=id
                    this.container=document.getElementById(id)
                    this.container.innerHTML = /*html*/`
                            <svg class="gauge-container" width="100%" height="100%" viewBox="0 0 100 100">
                            <rect style="fill: red;" width="100%" height="100%"/><!-- Pour visualisation du viewBox-->
                                    <g transform="translate(50 50)" transform-origin= "50 50" >
     
                                            <g class="ori">
                                                            <path style="fill:cyan;stroke:blue;stroke-width:1px;"
                                                                    d="
                                                                    M 40.95760221444959 28.678821817552304
                                                                    A 50 50 0 0 0 40.95760221444959 -28.678821817552304
                                                                    L 24.574561328669756 -17.20729309053138
                                                                    L 0 -10
                                                                    L 0 10
                                                                    L 24.574561328669756 17.20729309053138
                                                                    z
                                                                    "/>
                                                    <g class="gaugeG"   transform="translate(40 0)" transform-origin= "40 0" >
                                                            <circle class="gauge-bullCons"  cx="0" cy="0" r="10"  fill="#eee" stroke="#ccc" stroke-width="0.1 " ></circle>
                                                            <text class="gauge-cons-text" x="0"  y="0"   stroke-width="0.5"    font-size=" 0.5em"    text-align= "center"   text-anchor= "middle" >
                                                                    <tspan class="gauge-consLabel"></tspan>
                                                            </text>
                                                    </g>
                                            </g>
                                    </g>
                            </svg>
                            `
                    this.containerSVG=this.container.querySelector("svg")
                    this.bullCons = this.containerSVG.querySelector(".gauge-bullCons")
                    this.consLabel = this.containerSVG.querySelector(".gauge-consLabel")
                    this.gaugeconstext = this.containerSVG.querySelector(".gauge-cons-text")
                    this.gaugeG = this.containerSVG.querySelector(".gaugeG")
                    this.ori = this.containerSVG.querySelector(".ori")
     
            }
     
            ctrl(value){
                            this.bullCons.style.transform = `rotate(${value}deg)`
                            this.consLabel.innerHTML=value
                                            this.ori.style.transform = `
                                            rotate(${value}deg)
                            `;
                            this.gaugeconstext.style.transform = `
                                            rotate(${-value}deg)
                                            `;
            }
    }
    let gauge_di = {};//Dictionnaire des instances
    gauge_di[1] = new gauge({id : "gauge_svg"})
     
     window.onload = function () {
                    const container = document.querySelector(".gauge-container");
              const bullCons = container.querySelector(".gauge-bullCons");
              const consLabel = container.querySelector(".gauge-consLabel");
              const gaugeconstext = container.querySelector(".gauge-cons-text");
              const gaugeG = container.querySelector(".gaugeG");
              const ori = container.querySelector(".ori");
     
                    document.querySelector("#cons").addEventListener("change", event => {
                                            gauge_di[1].ctrl(event.currentTarget.value)
                    });
                     document.querySelector("#slide").addEventListener("mousedown", event => {
                                            document.querySelector("#slide").addEventListener("mousemove", event => {
                                            gauge_di[1].ctrl(event.currentTarget.value)
                                            });
                                    });
                     document.querySelector("#slide_width").addEventListener("mousedown", event => {
                                            document.querySelector("#slide_width").addEventListener("mousemove", event => {
                                            document.querySelector("#gauge_svg").style.width = `${event.currentTarget.value}px`
                                            document.querySelector("#gauge_svg").style.height = `400-${event.currentTarget.value}px`
                                            });
                                    });
                     document.querySelector("#slide_padding").addEventListener("mousedown", event => {
                                            document.querySelector("#slide_padding").addEventListener("mousemove", event => {
                                            document.querySelector("#gauge_svg").style.padding = `${event.currentTarget.value}px ${100-event.currentTarget.value}px`
                                            });
                                    });
        }
     
    </script>
        </main>
        <footer></footer>
      </body>
    </html>

  2. #2
    Expert éminent sénior
    Avatar de mathieu
    Profil pro
    Inscrit en
    Juin 2003
    Messages
    10 305
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2003
    Messages : 10 305
    Points : 15 633
    Points
    15 633
    Par défaut
    si par exemple la consigne est à 250, vous voulez que le svg soit moins large comme sur cette image par exemple ?
    Nom : dvlp_gauss_250.png
Affichages : 161
Taille : 2,1 Ko

  3. #3
    Membre du Club
    Homme Profil pro
    Technicien maintenance
    Inscrit en
    Août 2016
    Messages
    76
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Marne (Champagne Ardenne)

    Informations professionnelles :
    Activité : Technicien maintenance

    Informations forums :
    Inscription : Août 2016
    Messages : 76
    Points : 67
    Points
    67
    Par défaut
    Oui moins large mais également moins Haut.
    Je sais faire en manipulant les paramètres viewbox Mais le traitement des différents cas me semble être une usine à gaz. Et il est bien possible qu'une fonction existent pour résoudre ce problème.

  4. #4
    Expert éminent sénior
    Avatar de mathieu
    Profil pro
    Inscrit en
    Juin 2003
    Messages
    10 305
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2003
    Messages : 10 305
    Points : 15 633
    Points
    15 633
    Par défaut
    regardez cette méthode qui retourne le rectangle englobant la forme :
    https://developer.mozilla.org/en-US/...dingClientRect

  5. #5
    Modérateur

    Avatar de NoSmoking
    Homme Profil pro
    Inscrit en
    Janvier 2011
    Messages
    17 048
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Isère (Rhône Alpes)

    Informations forums :
    Inscription : Janvier 2011
    Messages : 17 048
    Points : 44 562
    Points
    44 562
    Par défaut
    Bonjour,
    in fine quel est le but ?

    Tu peux effectivement « recadrer » un <svg> sur un élément mais qu'en sera-t-il des transformations, car il semblerait bien que tu veuilles faire tourner ton élément.

    Il te faudra réactualiser à chaque modification et il y aura par la force des choses du « zoom/dézoom ».

    Et il est bien possible qu'une fonction existent pour résoudre ce problème.
    Bien souvent ce qui existe est ce que tu crées

    Voilà un exemple
    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
    /**
     * @param {SVGElement} elem - Élément devant être centré dans le SVG
     * @returns {String} viewBox appliquée
     */
    function ajusteViewBox(elem) {
      const oSvg = elem.ownerSVGElement;
      oSvg.removeAttribute("viewBox");
      // récup. dimensions DOM
      const boundsElem = elem.getBoundingClientRect();
      const ctm = oSvg.getScreenCTM();
      // conversion en unité SVG
      let pos = new DOMPointReadOnly(boundsElem.left, boundsElem.top);
      pos = pos.matrixTransform(ctm.inverse());
      // idem pour right et bottom
      let dim = new DOMPointReadOnly(boundsElem.left + boundsElem.width, boundsElem.top + boundsElem.height);
      dim = dim.matrixTransform(ctm.inverse());
     
      const viewBox = [
        pos.x,
        pos.y,
        dim.x - pos.x,
        dim.y - pos.y
      ].join(" ");
      oSvg.setAttribute("viewBox", viewBox);
      // à toutes fins utiles  
      return viewBox;
    }

  6. #6
    Membre du Club
    Homme Profil pro
    Technicien maintenance
    Inscrit en
    Août 2016
    Messages
    76
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Marne (Champagne Ardenne)

    Informations professionnelles :
    Activité : Technicien maintenance

    Informations forums :
    Inscription : Août 2016
    Messages : 76
    Points : 67
    Points
    67
    Par défaut
    Bonjour,
    J'ai mis du temps a vous répondre, je suis encore dessus, j’essaie les différentes méthode de transformation de svg et ça me prend beaucoup de temps.

    Bonjour,
    in fine quel est le but ?
    Deux objectif:
    -Apprendre la conception de svg.
    - Et pour ce faire je suis partie dans la création de classe de génération de jauge et de slider

    Pour créé une jauge je commence par un viewBox a échelle 100x100 et je déplace l'origine au centre. Ensuite je construit la gauge.
    En procédant ainsi, suivant la forme obtenu, il existent toute une zone de viewbox inutilisé. Le svg final étant sensé d’adapté à son contenaire, ces zone inutilisé crée des espaces inutile. Il me faut donc rogné les partie inutilisé.

    Peut-être me dirait vous que je ferais mieux d'utilisé un framwork?

    Je fait encore des test sur le sujet et sur les différentes transformation.
    Voici un code provisoire plus proche de ce que j'utilise pour généré mes svg.
    Code html : 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
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    <!DOCTYPE html>
    <html lang="">
      <head>
        <meta charset="utf-8">
        <title></title>
        <style>
                    td{
                            color:black;
                            border-style: solid;
                            border-width: 1px;
                            background:red;
                            border-color:black;
                    }
        </style>
      </head>
      <body>
        <header></header>
        <main>
    		<table>
    			<thead>
    				<tr>
    					<th>Sans rognage</th>
    					<th>Avec rognage</th>
    				<tr>
    			</thead>
    			<tbody>
    				<tr>
    					<td>
    						<table>
    							<tr>
    								<td id=11 width=100 height=100>/>
    								<td id=12 width=100 height=100/>
    							</tr>
    							<tr>
    								<td id=13 width=100 height=100/>
    								<td id=14 width=100 height=100/>
    							</tr>
    						</table>
    					</td>
    					<td>
    						<table>
    							<tr>
    								<td id=21 width=100 height=100/>
    								<td id=22 width=100 height=100/>
    							</tr>
    							<tr>
    								<td id=23 width=100 height=100/>
    								<td id=24 width=100 height=100/>
    							</tr>
    						</table>
    					</td>
    				</tr>
    			</tbody>
    		</table>
    <style>
     
    </style>
    <script>
    let GenAff_di = {};//Dictionnaire des instances des boutons généré automatiquement
     
    class GenAff {
            constructor({
                    id = "GenAff_D",
                    optionAff={
                            angle:270,//Largeur piste
                            angleRotation:90,//Angle de rotation globale
                            REchel:46,//Rayon piste hors maxi - mini
                            LEchel:11,//largeur piste hors maxi - mini
                            SEchel:1,//Largeur Contour Echel
                            },
            }={})
            {
                    this.id=id;
                    this.optionAff = optionAff
                    this.container=document.getElementById(this.id);
                    this.container.classList.add('GenAff');
                    this.#setHTML()
                    this.containerSVG=this.container.querySelector("svg")
                    this.containerSVG.classList.add('GenAff_svg')
                    this.containerGauge=this.container.querySelector(".GenAff_Gauge")
                    this.containerGaugeRot=this.container.querySelector(".GenAff_GaugeRot")
                    this.containerBord = document.createElementNS("http://www.w3.org/2000/svg", "path");
                    this.#drawGaugeTrack()
            }
            #setHTML() {
                    this.container.innerHTML = /*html*/`
     
     
                    <svg class="GenAff_svg" width="100%" height="100%">
     
                    <g      class="GenAff_Gauge"
                            transform=" translate(50 50)"
                            transform-origin=" 50 50"
                            >
                            <g      class="GenAff_GaugeRot">
     
                                    <g class="GenAff_Track"></g>
                            </g>
                    </g>
                    </svg>
                    `
            }
            #polarToCartesian(centerX, centerY, radius, angleInDegrees) {
                    let angleInRadians = (angleInDegrees) * Math.PI / 180.0
     
                    return {
                            x: centerX + (radius * Math.cos(angleInRadians)),
                            y: centerY + (radius * Math.sin(angleInRadians))
                    };
            }
            #describeArc(x, y, radius, startAngle, endAngle){
     
                    let start = this.#polarToCartesian(x, y, radius, endAngle);
                    let end = this.#polarToCartesian(x, y, radius, startAngle);
     
                    let largeArcFlag = endAngle - startAngle <= 180 ? "0" : "1";
     
                    let d = [
                    "M", start.x, start.y,
                    "A", radius, radius, 0, largeArcFlag, 0, end.x, end.y
                    ].join(" ");
     
            return d;
            }
     
            #drawGaugeTrack(){
     
     
                    const demiAngle = this.optionAff.angle/2
     
                    //rotation
                    this.containerGaugeRot.style.transform = `rotate(${this.optionAff.angleRotation}deg)`;
                    //Bordure
                    let xViewbox=100
                    let yViewbox=100
                    //const bord = document.createElementNS("http://www.w3.org/2000/svg", "path");
                    if (this.optionAff.angle<120){
                            let rptinter=this.optionAff.Rechel-this.optionAff.Lechel-(50-this.optionAff.Rechel)
                            let angleptinter=demiAngle+5
                            let pt1 = this.#polarToCartesian(0,0,rptinter,-angleptinter)
                            let pt2 = this.#polarToCartesian(0,0,rptinter,angleptinter)
                            this.containerBord.setAttribute("d",`
                            ${this.#describeArc(0, 0,  50 , -demiAngle-5, demiAngle+5,)}
                            L ${pt1['x']} ${pt1['y']}
                            L 0 -10
                            L 0 10
                            L ${pt2['x']} ${pt2['y']}
                            z
                            `);
                            xViewbox=50*Math.abs(Math.sin((90-demiAngle)))
                            yViewbox=50+this.optionAff.Raxe
    //                      this.containerGauge.style.transform = `translate(${50-xViewbox/2}px, 50px)`;
                    }
     
    //      this.containerSVG.setAttribute("viewBox",`0 0 ${xViewbox} ${yViewbox}`)
            this.containerGaugeRot.insertAdjacentElement('afterbegin',this.containerBord);
            this.containerBord.setAttribute("class", "GenAff_Bord");
            this.containerBord.setAttribute("stroke", "lime");
            this.containerBord.setAttribute("fill", "lime");
            }
     
    }
     
    GenAff_di[11] = new GenAff({
                                    id:11,
                                    optionAff:{
                                            angle:60,
                                            angleRotation:0,
                                            Rechel:46,//Rayon echelle hors mini - maxi
                                            Lechel:12,//largeur echelle hors mini - maxi
                                            SEchel:1,//Largeur Contour Echel
                                            }
                                    })
    GenAff_di[12] = new GenAff({
                                    id:12,
                                    optionAff:{
                                            angle:60,
                                            angleRotation:90,
                                            Rechel:46,//Rayon echelle hors mini - maxi
                                            Lechel:12,//largeur echelle hors mini - maxi
                                            SEchel:1,//Largeur Contour Echel
                                            }
                                    })
    GenAff_di[13] = new GenAff({
                                    id:13,
                                    optionAff:{
                                            angle:60,
                                            angleRotation:180,
                                            Rechel:46,//Rayon echelle hors mini - maxi
                                            Lechel:12,//largeur echelle hors mini - maxi
                                            SEchel:1,//Largeur Contour Echel
                                            }
                                    })
    GenAff_di[14] = new GenAff({
                                    id:14,
                                    optionAff:{
                                            angle:60,
                                            angleRotation:270,
                                            Rechel:46,//Rayon echelle hors mini - maxi
                                            Lechel:12,//largeur echelle hors mini - maxi
                                            SEchel:1,//Largeur Contour Echel
                                            }
                                    })
    </script>
        </main>
        <footer></footer>
      </body>
    </html>

  7. #7
    Membre du Club
    Homme Profil pro
    Technicien maintenance
    Inscrit en
    Août 2016
    Messages
    76
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Marne (Champagne Ardenne)

    Informations professionnelles :
    Activité : Technicien maintenance

    Informations forums :
    Inscription : Août 2016
    Messages : 76
    Points : 67
    Points
    67
    Par défaut
    La méthode fourni par nosmoking est vraiment efficace et peut servir comme exemple pour la conversion de position des éléments svg.
    J'ai tendance a ne pas vouloirs utilisé Matrix, mais visiblement c'est un tord.

    Voici le code final pour exemple.
    Et merci a vous.
    Code html : 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
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    <!DOCTYPE html>
    <html lang="">
      <head>
        <meta charset="utf-8">
        <title></title>
        <style>
                    td{
                            color:black;
                            border-style: solid;
                            border-width: 1px;
                            background:red;
                            border-color:black;
                    }
        </style>
      </head>
      <body>
        <header></header>
        <main>
    		<table>
    			<thead>
    				<tr>
    					<th>Sans rognage</th>
    					<th>Avec rognage</th>
    				<tr>
    			</thead>
    			<tbody>
    				<tr>
    					<td>
    						<table>
    							<tr>
    								<td id=11 width=100 height=100>/>
    								<td id=12 width=100 height=100/>
    							</tr>
    							<tr>
    								<td id=13 width=100 height=100/>
    								<td id=14 width=100 height=100/>
    							</tr>
    						</table>
    					</td>
    					<td>
    						<table>
    							<tr>
    								<td id=21 width=100 height=100/>
    								<td id=22 width=100 height=100/>
    							</tr>
    							<tr>
    								<td id=23 width=100 height=100/>
    								<td id=24 width=100 height=100/>
    							</tr>
    						</table>
    					</td>
    				</tr>
    			</tbody>
    		</table>
    <style>
     
    </style>
    <script>
    let GenAff_di = {};//Dictionnaire des instances des boutons généré automatiquement
     
    class GenAff {
            constructor({
                    id = "GenAff_D",
                    optionAff={
                            angle:270,//Largeur piste
                            angleRotation:90,//Angle de rotation globale
                            REchel:46,//Rayon piste hors maxi - mini
                            LEchel:11,//largeur piste hors maxi - mini
                            SEchel:1,//Largeur Contour Echel
                            Rognage:true,//rognage actif
                            },
            }={})
            {
                    this.id=id;
                    this.optionAff = optionAff
                    this.container=document.getElementById(this.id);
                    this.container.classList.add('GenAff');
                    this.#setHTML()
                    this.containerSVG=this.container.querySelector("svg")
                    this.containerSVG.classList.add('GenAff_svg')
                    this.containerGauge=this.container.querySelector(".GenAff_Gauge")
                    this.containerGaugeRot=this.container.querySelector(".GenAff_GaugeRot")
                    this.containerBord = document.createElementNS("http://www.w3.org/2000/svg", "path");
                    this.#drawGaugeTrack()
            }
            #setHTML() {
                    this.container.innerHTML = /*html*/`
     
     
                    <svg class="GenAff_svg" width="100%" height="100%" viewBox="0 0 100 100">
                            <rect class="rectSVG" width="100%" height="100%" fill="transparent" stroke="transparent" stroke-width="0px"/><!-- Pour visualisation du viewBox-->
     
                            <g      class="GenAff_Gauge"
                                    transform=" translate(50 50)"
                                    transform-origin=" 50 50"
                                    >
                                    <g      class="GenAff_GaugeRot">
     
                                            <g class="GenAff_Track"></g>
                                    </g>
                            </g>
                    </svg>
                    `
            }
            #polarToCartesian(centerX, centerY, radius, angleInDegrees) {
                    let angleInRadians = (angleInDegrees) * Math.PI / 180.0
     
                    return {
                            x: centerX + (radius * Math.cos(angleInRadians)),
                            y: centerY + (radius * Math.sin(angleInRadians))
                    };
            }
            #describeArc(x, y, radius, startAngle, endAngle){
     
                    let start = this.#polarToCartesian(x, y, radius, endAngle);
                    let end = this.#polarToCartesian(x, y, radius, startAngle);
     
                    let largeArcFlag = endAngle - startAngle <= 180 ? "0" : "1";
     
                    let d = [
                    "M", start.x, start.y,
                    "A", radius, radius, 0, largeArcFlag, 0, end.x, end.y
                    ].join(" ");
     
            return d;
            }
     
            #drawGaugeTrack(){
     
     
                    const demiAngle = this.optionAff.angle/2
     
                    //rotation
                    this.containerGaugeRot.style.transform = `rotate(${this.optionAff.angleRotation}deg)`;
                    //Bordure
                    if (this.optionAff.angle<120){
                            let rptinter=this.optionAff.Rechel-this.optionAff.Lechel-(50-this.optionAff.Rechel)
                            let angleptinter=demiAngle+5
                            let pt1 = this.#polarToCartesian(0,0,rptinter,-angleptinter)
                            let pt2 = this.#polarToCartesian(0,0,rptinter,angleptinter)
                            this.containerBord.setAttribute("d",`
                            ${this.#describeArc(0, 0,  50-(this.optionAff.SEchel/2) , -demiAngle-5, demiAngle+5,)}
                            L ${pt1['x']} ${pt1['y']}
                            L 0 -10
                            L 0 10
                            L ${pt2['x']} ${pt2['y']}
                            z
                            `);
                    }
                    this.containerGaugeRot.insertAdjacentElement('afterbegin',this.containerBord);
                    this.containerBord.setAttribute("class", "GenAff_Bord");
                    this.containerBord.setAttribute("stroke", "lime");
                    this.containerBord.setAttribute("fill", "lime");
     
                    //rognage
                    let rectEncadr= this.containerBord.getBoundingClientRect()
                    let contRectSVG=this.container.querySelector(".rectSVG")
                    let rectSVG=contRectSVG.getBoundingClientRect()
     
                     //visu rect encadrée
                    const contRectEncadr = document.createElementNS("http://www.w3.org/2000/svg", "rect");
                    contRectEncadr.setAttribute("x", rectEncadr.left-rectSVG.left);
                    contRectEncadr.setAttribute("y", rectEncadr.top-rectSVG.top);
                    contRectEncadr.setAttribute("width", rectEncadr.width);
                    contRectEncadr.setAttribute("height", rectEncadr.height);
                    contRectEncadr.setAttribute("fill", "yellow");
                    contRectEncadr.setAttribute("stroke", "transparent");
                    contRectEncadr.setAttribute("stroke-width", "0px");
                    this.containerSVG.insertAdjacentElement('afterbegin',contRectEncadr);
     
                    //
                    if (this.optionAff.Rognage){
                            this.#ajusteViewBox(this.containerBord)
                    }
            }
            /**
            * @param {SVGElement} elem - Élément devant être centré dans le SVG
            * @returns {String} viewBox appliquée
            */
            #ajusteViewBox(elem) {
                    const oSvg = elem.ownerSVGElement;
                    oSvg.removeAttribute("viewBox");
                    // récup. dimensions DOM
                    const boundsElem = elem.getBoundingClientRect();
                    const ctm = oSvg.getScreenCTM();
                    // conversion en unité SVG
                    let pos = new DOMPointReadOnly(boundsElem.left, boundsElem.top);
                    pos = pos.matrixTransform(ctm.inverse());
                    // idem pour right et bottom
                    let dim = new DOMPointReadOnly(boundsElem.left + boundsElem.width, boundsElem.top + boundsElem.height);
                    dim = dim.matrixTransform(ctm.inverse());
     
                    const viewBox = [
                            pos.x,
                            pos.y,
                            dim.x - pos.x,
                            dim.y - pos.y
                    ].join(" ");
                    oSvg.setAttribute("viewBox", viewBox);
                    // à toutes fins utiles
                    return viewBox;
            }
    }
     
     
    GenAff_di[11] = new GenAff({
                                    id:11,
                                    optionAff:{
                                            angle:60,
                                            angleRotation:0,
                                            Rechel:46,//Rayon echelle hors mini - maxi
                                            Lechel:12,//largeur echelle hors mini - maxi
                                            SEchel:1,//Largeur Contour Echel
                                            Rognage:false,//rognage actif
                                            }
                                    })
    GenAff_di[12] = new GenAff({
                                    id:12,
                                    optionAff:{
                                            angle:60,
                                            angleRotation:90,
                                            Rechel:46,//Rayon echelle hors mini - maxi
                                            Lechel:12,//largeur echelle hors mini - maxi
                                            SEchel:1,//Largeur Contour Echel
                                            Rognage:false,//rognage actif
                                            }
                                    })
    GenAff_di[13] = new GenAff({
                                    id:13,
                                    optionAff:{
                                            angle:60,
                                            angleRotation:180,
                                            Rechel:46,//Rayon echelle hors mini - maxi
                                            Lechel:12,//largeur echelle hors mini - maxi
                                            SEchel:1,//Largeur Contour Echel
                                            Rognage:false,//rognage actif
                                            }
                                    })
    GenAff_di[14] = new GenAff({
                                    id:14,
                                    optionAff:{
                                            angle:60,
                                            angleRotation:270,
                                            Rechel:46,//Rayon echelle hors mini - maxi
                                            Lechel:12,//largeur echelle hors mini - maxi
                                            SEchel:1,//Largeur Contour Echel
                                            Rognage:false,//rognage actif
                                            }
                                    })
    GenAff_di[21] = new GenAff({
                                    id:21,
                                    optionAff:{
                                            angle:60,
                                            angleRotation:0,
                                            Rechel:46,//Rayon echelle hors mini - maxi
                                            Lechel:12,//largeur echelle hors mini - maxi
                                            SEchel:1,//Largeur Contour Echel
                                            Rognage:true,//rognage actif
                                            }
                                    })
    GenAff_di[22] = new GenAff({
                                    id:22,
                                    optionAff:{
                                            angle:60,
                                            angleRotation:90,
                                            Rechel:46,//Rayon echelle hors mini - maxi
                                            Lechel:12,//largeur echelle hors mini - maxi
                                            SEchel:1,//Largeur Contour Echel
                                            Rognage:true,//rognage actif
                                            }
                                    })
    GenAff_di[23] = new GenAff({
                                    id:23,
                                    optionAff:{
                                            angle:60,
                                            angleRotation:180,
                                            Rechel:46,//Rayon echelle hors mini - maxi
                                            Lechel:12,//largeur echelle hors mini - maxi
                                            SEchel:1,//Largeur Contour Echel
                                            Rognage:true,//rognage actif
                                            }
                                    })
    GenAff_di[24] = new GenAff({
                                    id:24,
                                    optionAff:{
                                            angle:60,
                                            angleRotation:270,
                                            Rechel:46,//Rayon echelle hors mini - maxi
                                            Lechel:12,//largeur echelle hors mini - maxi
                                            SEchel:1,//Largeur Contour Echel
                                            Rognage:true,//rognage actif
                                            }
                                    })
    </script>
        </main>
        <footer></footer>
      </body>
    </html>

  8. #8
    Modérateur

    Avatar de NoSmoking
    Homme Profil pro
    Inscrit en
    Janvier 2011
    Messages
    17 048
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Isère (Rhône Alpes)

    Informations forums :
    Inscription : Janvier 2011
    Messages : 17 048
    Points : 44 562
    Points
    44 562
    Par défaut
    Il me faut donc rogné les partie inutilisé.
    en fait au début il faut surtout s'arranger pour ne pas en créer, toutes transformations pouvant devenir difficiles à contrôler par la suite et dans ce cas la « matrice » est importante.

    Il manque pour moi dans l’exemple que tu as mis des éléments avec un angle de rotation à 45°, 135°, 225° et 315°.
    Tu observeras que la viewBox est encore différente.

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. (WDM) Adapter une fenêtre à son contenu (iOS)
    Par Bobot dans le forum Windev Mobile
    Réponses: 0
    Dernier message: 21/09/2015, 14h21
  2. DIV absolute qui s'adapte en hauteur à son contenu
    Par Khleo dans le forum Mise en page CSS
    Réponses: 2
    Dernier message: 07/06/2011, 20h24
  3. Adapter une DIV à son contenu
    Par miltonis dans le forum Mise en page CSS
    Réponses: 6
    Dernier message: 29/04/2011, 12h14
  4. Adapter la taille d'un JPanel en fonction de son contenu
    Par SeaShell dans le forum AWT/Swing
    Réponses: 3
    Dernier message: 20/04/2008, 22h49
  5. Réponses: 3
    Dernier message: 10/08/2007, 13h45

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