forked from Raphbub/datavisenchiffres
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtemps_trajet.html
478 lines (419 loc) · 18.4 KB
/
temps_trajet.html
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
<!DOCTYPE html>
<head>
<title>Temps de trajet journalier moyen</title>
<script src="libs/d3.v7.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="container"></div>
<div style="margin-top: 400px;">
<h5 class="com">Commentaire et améliorations</h5>
<p>
Cette visualisation représente le temps de trajet journalier moyen au total et par mode de transport,
en Valais, toutes activités confondues (travail, loisirs, etc.).
C'est une façon plus originale de représenter une quantité qu'un simple graphique en barre.
Ici l'animation est un grand plus (mais a fait remonter pas mal de mauvais souvenirs liés au
cercle trigonométrique), car elle permet de mieux comprendre que la grande horloge représente
le total et qu'il est supérieur à une heure (un tour de cadran).
Il serait également intéressant d'y coupler la distance moyenne par type de transport
(qui a dû être abandonnée faute de place).
</p>
<p>
Pour améliorer cette visualisation, il faudrait construire la page de façon à avoir l'entièreté
des informations disponibles. Un texte explicatif sur ce qui est montré ou quelque chose de plus
construit et accompagné comme un scrollytelling pourrait valoriser le travail sur les horloges.
</p>
<button onclick="location.href='index.html'">Retour à l'accueil</button>
</div>
<script>
/* Ce script a été construit en grande partie par un dialogue avec ChatGPT 3.5 et 4o plus récemment
et des ajustements très réguliers pour obtenir qqch de fonctionnel. Les parties
utilisées plus ou moins directement sont mentionnées telles quelles
Les liens suivants ont également été utilisés :
- https://observablehq.com/@d3/simple-clock
- https://observablehq.com/@drio/lets-build-an-analog-clock */
// Pour enregistrer les horloges
const clocks = [];
// Création d'une horloge dans un container, avec h, l, place dans le svg et label du type
function createClock(container, width, height, x, y, label) {
const radius = Math.min(width, height) / 2;
// Créer un svg par horloge
const svg = container.append("svg")
.attr("width", width)
.attr("height", height + 30) // Décaler pour le label
.style("position", "absolute")
.style("left", `${x}px`)
.style("top", `${y}px`);
// Label au-dessus de l'horloge
svg.append("text")
.attr("x", width / 2)
.attr("y", 20)
.attr("text-anchor", "middle")
.attr("font-family", "Arial")
.attr("font-size", "16px")
.attr("fill", "#262626")
.text(label);
// Ajouter un groupe au centre du svg
const g = svg.append("g")
.attr("transform", `translate(${width / 2}, ${(height + 30) / 2 + 10})`);
// Contour horloge
g.append("circle")
.attr("r", radius)
.attr("fill", "none")
.attr("stroke", "#4c4c4c")
.attr("stroke-width", 1);
// Marques des heures
const hourTicks = d3.range(0, 12).map(d => {
return {
angle: (d / 12) * 2 * Math.PI,
x1: radius * 0.97 * Math.sin((d / 12) * 2 * Math.PI),
y1: -radius * 0.97 * Math.cos((d / 12) * 2 * Math.PI),
x2: radius * 0.85 * Math.sin((d / 12) * 2 * Math.PI),
y2: -radius * 0.85 * Math.cos((d / 12) * 2 * Math.PI)
};
});
g.selectAll(".hour-tick")
.data(hourTicks)
.enter()
.append("line")
.attr("class", "hour-tick")
.attr("x1", d => d.x1)
.attr("y1", d => d.y1)
.attr("x2", d => d.x2)
.attr("y2", d => d.y2)
.attr("stroke", "#4c4c4c")
.attr("stroke-width", 2);
// Marques des minutes
const minuteTicks = d3.range(0, 60).filter(d => d % 5 !== 0).map(d => {
return {
angle: (d / 60) * 2 * Math.PI,
x1: radius * 0.95 * Math.sin((d / 60) * 2 * Math.PI),
y1: -radius * 0.95 * Math.cos((d / 60) * 2 * Math.PI),
x2: radius * 0.9 * Math.sin((d / 60) * 2 * Math.PI),
y2: -radius * 0.9 * Math.cos((d / 60) * 2 * Math.PI)
};
});
g.selectAll(".minute-tick")
.data(minuteTicks)
.enter()
.append("line")
.attr("class", "minute-tick")
.attr("x1", d => d.x1)
.attr("y1", d => d.y1)
.attr("x2", d => d.x2)
.attr("y2", d => d.y2)
.attr("stroke", "#4c4c4c")
.attr("stroke-width", 1);
// Ajouter le svg et rayon dans les horloges
clocks.push({ svg: g, radius });
}
// Initialiser l'horloge et ajouter un polygone de couleur pour le fill
function initClock(clock, color) {
// Récupérer le rayon
const radius = clock.radius;
// Enlever les éventuels éléments de temps présents
clock.svg.selectAll(".hour-hand, .minute-hand, .minute-fill").remove();
// Dessiner l'aiguille des heures
clock.svg.append("line")
.attr("class", "hour-hand")
.attr("x1", 0)
.attr("y1", 0)
.attr("x2", 0)
.attr("y2", -radius * 0.5)
.attr("stroke", "black")
.attr("stroke-width", 3)
.attr("stroke-linecap", "round")
.attr("transform", `rotate(0)`);
// Dessiner l'aiguille des minutes
clock.svg.append("line")
.attr("class", "minute-hand")
.attr("x1", 0)
.attr("y1", 0)
.attr("x2", 0)
.attr("y2", -radius * 0.7)
.attr("stroke", "black")
.attr("stroke-width", 2.25)
.attr("stroke-linecap", "round")
.attr("transform", `rotate(0)`);
// Ajouter un petit "bouton" à la jointure des aiguilles
clock.svg.append("circle")
.attr("class", "center-circle")
.attr("cx", 0)
.attr("cy", 0)
.attr("r", 2.5)
.attr("fill", "black");
// Ajouter le path de couleur
clock.currentFillPath = createFillPath(clock, color);
clock.previousMinuteAngle = 0;
clock.fillColor = color;
}
// Créer un fill path pour marquer le temps couvert d'une certaine couleur
function createFillPath(clock, color) {
return clock.svg.append("path")
.attr("class", "minute-fill")
.attr("fill", color)
.attr("d", "");
}
// Ajuster le fill path selon les angles
function updateFillPath(fillPath, startAngle, endAngle, radius, from0 = false) {
// Savoir s'il faut dessiner un cercle "contenu" ou non
let largeArcFlag = endAngle - startAngle > Math.PI ? 1 : 0;
// let largeArcFlag = Math.abs(endAngle - startAngle) > Math.PI ? 1 : 0;
const startX = radius * Math.sin(startAngle);
const startY = -radius * Math.cos(startAngle);
const endX = radius * Math.sin(endAngle);
const endY = -radius * Math.cos(endAngle);
// Ajout pour contrer le "faux" calcul du flag quand on continue le cercle après 0
if (from0) {
largeArcFlag = 0;
}
// Créer les coordonnées du path
fillPath.attr("d", `M 0,0 L ${startX},${startY} A ${radius},${radius} 0 ${largeArcFlag},1 ${endX},${endY} Z`);
}
// Déplacer les aiguilles et la surface d'une horloge, à partir de 0 ou de la position actuelle
function runClock(clock, minutes, fromCurrentPosition = false, color) {
// Définir les temps de transition
const transitionDuration = minutes * 90;
const transDurationPath = (minutes > 60) ? transitionDuration / 90 * 60 : transitionDuration;
let startHourAngle = 0;
let startMinuteAngle = 0;
// Récupérer les infos si on continue depuis l'ancien
if (fromCurrentPosition) {
const currentHourTransform = clock.svg.selectAll(".hour-hand").attr("transform");
const currentMinuteTransform = clock.svg.selectAll(".minute-hand").attr("transform");
if (currentHourTransform) {
startHourAngle = parseFloat(currentHourTransform.match(/rotate\(([-\d.]+)\)/)[1]);
}
if (currentMinuteTransform) {
startMinuteAngle = parseFloat(currentMinuteTransform.match(/rotate\(([-\d.]+)\)/)[1]);
clock.previousMinuteAngle = startMinuteAngle;
}
}
// Calculer et convertir les éléments pour les angles
const hours = Math.floor(minutes / 60);
const remainingMinutes = minutes % 60;
const hourAngle = startHourAngle + (hours + remainingMinutes / 60) * 30;
const minuteAngle = startMinuteAngle + remainingMinutes * 6;
const fullTurns = Math.floor(minutes / 60);
const endMinuteAngle = minuteAngle * Math.PI / 180;
// Faire tourner l'aiguille des heures
const hourHandTransition = clock.svg.selectAll(".hour-hand")
.transition()
.ease(d3.easeLinear)
.duration(transitionDuration)
.attrTween("transform", function() {
const interpolate = d3.interpolateNumber(startHourAngle, hourAngle);
return function(t) {
return `rotate(${interpolate(t)})`;
};
});
// Faire tourner l'aiguille des minutes
const minuteHandTransition = clock.svg.selectAll(".minute-hand")
.transition()
.ease(d3.easeLinear)
.duration(transitionDuration)
.attrTween("transform", function() {
const interpolate = d3.interpolateNumber(startMinuteAngle, minuteAngle + (360 * fullTurns));
return function(t) {
return `rotate(${interpolate(t)})`;
};
});
// Récupérer le fill path de l'horloge
let currentFillPath = clock.currentFillPath;
// S'il y a plus d'une heure, il faut rajouter plusieurs fill path
if (fullTurns > 0) {
if (currentFillPath) {
currentFillPath
.transition()
.ease(d3.easeLinear)
.duration(transDurationPath / (fullTurns + 1))
.attrTween("d", function() {
const interpolate = d3.interpolateNumber(clock.previousMinuteAngle * Math.PI / 180, Math.PI * 2);
return function(t) {
const currentEndAngle = interpolate(t);
updateFillPath(currentFillPath, 0, currentEndAngle, clock.radius);
return currentFillPath.attr("d");
};
});
}
// Un par tour additionnel
for (let i = 1; i <= fullTurns; i++) {
const fillPath = createFillPath(clock, color);
fillPath
.transition()
.ease(d3.easeLinear)
.duration(transitionDuration / fullTurns)
.attrTween("d", function() {
const interpolate = d3.interpolateNumber(0, Math.PI * 2);
return function(t) {
const currentEndAngle = interpolate(t);
updateFillPath(fillPath, 0, currentEndAngle, clock.radius);
return fillPath.attr("d");
};
});
// Mettre à jour le fill path en cours
clock.currentFillPath = fillPath;
}
}
// S'il reste des minutes, mettre à jour le fill path avec
if (remainingMinutes > 0) {
const previousAngleInRadians = clock.previousMinuteAngle * Math.PI / 180;
// S'il y a une transition d'un côté à l'autre du 0
if (clock.previousMinuteAngle < 360 && minuteAngle >= 360) {
// Calculer les minutes et temps de transition
const minutesPastZero = remainingMinutes - (60 - (clock.previousMinuteAngle / 6))
const firstStepDuration = (60 - (clock.previousMinuteAngle / 6)) * 90;
const remainingDuration = minutesPastZero * 90;
// Compléter le fill path jusqu'à 0
currentFillPath
.transition()
.ease(d3.easeLinear)
.duration(firstStepDuration)
.attrTween("d", function() {
const interpolate = d3.interpolateNumber(previousAngleInRadians, Math.PI * 2);
return function(t) {
const currentEndAngle = interpolate(t);
updateFillPath(currentFillPath, 0, currentEndAngle, clock.radius);
return currentFillPath.attr("d");
};
})
// Une fois la première étape faite, compléter du 0 à l'autre côté dans un nouveau fill path
.on("end", function() {
const newFillPath = createFillPath(clock, color);
newFillPath
.transition()
.ease(d3.easeLinear)
.duration(remainingDuration)
.attrTween("d", function() {
const interpolate = d3.interpolateNumber(0, minutesPastZero * 6 * Math.PI / 180);
return function(t) {
const currentEndAngle = interpolate(t);
updateFillPath(newFillPath, 0, currentEndAngle, clock.radius);
return newFillPath.attr("d");
};
});
clock.currentFillPath = newFillPath;
});
} else if (clock.previousMinuteAngle == 360 | clock.previousMinuteAngle == 0) {
// Si on (re)part de 0, commencer...depuis 0
currentFillPath
.transition()
.ease(d3.easeLinear)
.duration(transDurationPath / (fullTurns + 1))
.attrTween("d", function() {
const interpolate = d3.interpolateNumber(previousAngleInRadians, endMinuteAngle);
console.log(previousAngleInRadians);
console.log(endMinuteAngle);
return function(t) {
const currentEndAngle = interpolate(t);
// console.log(currentEndAngle);
updateFillPath(currentFillPath, 0, currentEndAngle, clock.radius);
return currentFillPath.attr("d");
};
});
clock.currentFillPath = currentFillPath;
}
else {
// Sinon reprendre depuis la dernière mesure
currentFillPath
.transition()
.ease(d3.easeLinear)
.duration(transDurationPath / (fullTurns + 1))
.attrTween("d", function() {
const interpolate = d3.interpolateNumber(previousAngleInRadians, endMinuteAngle);
console.log(previousAngleInRadians);
console.log(endMinuteAngle);
return function(t) {
const currentEndAngle = interpolate(t);
// console.log(currentEndAngle);
updateFillPath(currentFillPath, 0, currentEndAngle, clock.radius, from0 = true);
return currentFillPath.attr("d");
};
});
// Ajuste le fill path de l'horloge
clock.currentFillPath = currentFillPath;
}
}
// Mettre à jour pour le prochain tour
clock.previousMinuteAngle = minuteAngle + (360 * fullTurns);
// Pour la synchronisation
return {
hourHandTransition,
minuteHandTransition
};
}
// Définir la variable container
const container = d3.select("#container");
// Créer la grande horloge
createClock(container, 300, 300, 0, 0, "Temps de trajet journalier moyen total");
// Créer les 4 petites
const smallClockSize = 125;
createClock(container, smallClockSize, smallClockSize, 350, 10, "Trsp. ind. motor."); // Top-right clock
createClock(container, smallClockSize, smallClockSize, 350 + smallClockSize + 50, 10, "Mobilité douce"); // Top-right second clock
createClock(container, smallClockSize, smallClockSize, 350, smallClockSize + 50, "Trsp. publics"); // Bottom-right clock
createClock(container, smallClockSize, smallClockSize, 350 + smallClockSize + 50, smallClockSize + 50, "Autres"); // Bottom-right second clock
// Les initialiser avec leur couleur respective
initClock(clocks[0], "rgba(255, 165, 155, 0.5)");
initClock(clocks[1], "rgba(208, 118, 185, 0.5)");
initClock(clocks[2], "rgba(128, 204, 116, 0.5)");
initClock(clocks[3], "rgba(104, 209, 244, 0.5)");
initClock(clocks[4], "rgba(134, 135, 139, 0.5)");
// Partiellement généré avec Chat-GPT 3.5, "how can I animate clocks two by two and make sure it is finished
// before launching the next clocks animation ?"
function animateClocks(clock1, clock2, minutes) {
return new Promise((resolve) => {
// La grande continue depuis le dernier arrêt
const transitionsClock1 = runClock(clock1, minutes, fromCurrentPosition = true, clock1.fillColor);
const transitionsClock2 = runClock(clock2, minutes, false, clock2.fillColor);
// Wait for both clocks to finish
Promise.all([
transitionsClock1.hourHandTransition.end(),
transitionsClock1.minuteHandTransition.end(),
transitionsClock2.hourHandTransition.end(),
transitionsClock2.minuteHandTransition.end()
]).then(resolve);
});
}
// Ajouter les minutes sous le centre de l'horloge
function addNumberToClock(clock, number, x = 0, y = 35) {
clock.svg.append("text")
.attr("class", "clock-number")
.attr("x", x)
.attr("y", y)
.attr("text-anchor", "middle")
.attr("alignment-baseline", "middle")
.attr("font-size", clock.radius * 0.3)
.attr("fill", "black")
.attr("font-family", "Arial")
.attr("font-weight", "bold")
.text(number);
}
// Animation principale
function animateTravelTime() {
// TIM
animateClocks(clocks[0], clocks[1], 39.6)
// MD
.then(() => {
addNumberToClock(clocks[1], "39.6'")
return animateClocks(clocks[0], clocks[2], 31.7)
})
// // TP
.then(() => {
addNumberToClock(clocks[2], "31.7'", x = 20)
return animateClocks(clocks[0], clocks[3], 5.8)
})
// Autres
.then(() => {
addNumberToClock(clocks[3], "5.8'")
return animateClocks(clocks[0], clocks[4], 2.7)
})
.then(() => {
addNumberToClock(clocks[4], "2.7'")
addNumberToClock(clocks[0], "1h19.8", x = 0, y = 100)
})
}
setTimeout(() => {
animateTravelTime();
}, 750);
</script>
</body>