SVG JavaScript Анимированные стрелки отсутствуютHtml

Программисты Html
Ответить
Anonymous
 SVG JavaScript Анимированные стрелки отсутствуют

Сообщение Anonymous »

Я пытаюсь оживить серию стрел между текстовыми полями в HTML -файле. Текстовые поля получают струны JSON, отправляемые через вызовы API. Эта часть работает отлично. Однако я пытаюсь оживить четыре стрелки между коробками, чтобы проиллюстрировать и синхризировать с обменом данными, и я не могу заставить свои стрелки появиться. В Chrome Inspector нет сообщений об ошибках, и я вижу, что стрелки становятся активными и неактивными, но не появляется ни одна, что заставляет меня думать, что это простая проблема, возможно, где -то переключатель непрозрачности. В литературе неясно возможные решения. В чем проблема с кодом JS, что стрелки не будут появляться или оживить? Любая помощь будет получена. Я заключил соответствующие HTML и JS моей страницы.

Код: Выделить всё

const sp_base = "http://localhost:8080";
const ttp_base = "http://localhost:8090";

const delay = ms => new Promise(res => setTimeout(res, ms));

function show(id, data) {
document.getElementById(id).textContent =
(typeof data === "string" ? data : JSON.stringify(data, null, 2));
}

function setStatus(text) {
document.getElementById("statusLine").textContent = text;
}

function resetDemo() {
show("userBox", "// waiting…");
show("spBox", "// waiting…");
show("ttpBox", "// waiting…");
setStatus("Ready to start");
document.querySelectorAll("svg.arrow path").forEach(p => p.classList.remove("active"));
console.log("Demo Reset");
}

function animateArrow(id) {
const path = document.getElementById(id);
console.log("Arrow animated");
if (!path) {
console.error(`Arrow with id "${id}" not found!`);
return;
}

//Reset Animation

path.style.strokeDashoffset = "300";
void path.offsetWidth; // Force reflow
console.log("Animation Restart");

//trigger animation
path.classList.add("active");
console.log("Animation Triggered");

//remove active status after animation finish
setTimeout(() => path.classList.remove("active"), 1000);
}

// Ensure DOM is ready
document.addEventListener("DOMContentLoaded", () => {
document.getElementById("runDemo").onclick = async () =>  {
resetDemo();
setStatus("Step 1: User → Service Provider");
show("userBox", "Running demo...");
//await delay(5000);

try {
// Step 1
animateArrow("arrow1");

await delay(5000);

const uidResp = 'example-guid';
/* removed for demo
//this logic is working only the animation is missing
const uidResp = await fetch(`${sp_base}/UID/issue`, {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({ dln: dln, sh: shx, audience: "sp"})
}).then(r=>r.json());
*/

show("spBox", uidResp);

await delay(5000);

// Step 2
setStatus("Step 2: Service Provider → User (UID issued)");
animateArrow("arrow2");
show("userBox", {
message: "Received signed UID from SP",
uid: uidResp
});

await delay(5000);

// Step 3
setStatus("Step 3: User → TTP (send UID)");
animateArrow("arrow3");

const ttpResp = 'example-token';

/* removed for demo
const ttpResp = await fetch(`${ttp_base}/token/issue`, {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({
uid: uidResp.uid,
signature: uidResp.signature,
signer: uidResp.signer
})
}).then(r=>r.json());
*/

show("ttpBox", ttpResp);

await delay(5000);

// Step 4
setStatus("Step 4: TTP → User (note issued)");
animateArrow("arrow4");
show("userBox", {
message: "Received note from TTP after verification",
token: ttpResp
});

setStatus("Demo complete ✅");

} catch (err) {
console.error(err);
show("userBox", {
error: err.message
});
setStatus("Error: " + err.message);
}
};
});
document.getElementById("resetDemo").onclick = resetDemo;< /code>
body {
font-family: sans-serif;
background: #f8f8f8;
padding: 1rem;
}

h1 {
text-align: center;
}

.buttons {
text-align: center;
margin: 1rem 0;
}

button {
margin: 0.3rem;
padding: 0.5rem 1rem;
font-size: 1rem;
border-radius: 4px;
cursor: pointer;
}

#statusLine {
text-align: center;
font-weight: bold;
font-size: 1.1rem;
margin-bottom: 0.5rem;
color: #1976d2;
}

.container {
position: relative;
width: 100%;
}

.boxes {
display: flex;
justify-content: space-around;
margin-top: 1rem;
position: relative;
z-index: 2;
}

.box {
width: 28%;
background: white;
border: 2px solid #444;
border-radius: 6px;
padding: 0.5rem;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.title {
font-weight: bold;
text-align: center;
margin-bottom: 0.5rem;
}

pre {
background: #f0f0f0;
height: 200px;
overflow: auto;
padding: 0.5rem;
border-radius: 4px;
font-size: 0.8rem;
}

/* Arrow styling */
svg.arrow {
position: absolute;
top: 290px;
width: 100%;
height: 50px;
overflow: visible;
z-index: 1;
}

svg.arrow path {
transition: stroke-dashoffset 1s ease-in-out;
stroke: #1976d2;
stroke-width: 3;
fill: none;
marker-end: url(#arrowhead);
opacity: 1;
/* hidden until animated */
}

path.active {
stroke: #4CAF50;
stroke-width: 2px;
stroke-dasharray: 300;
stroke-dashoffset: 300;
opacity: 1;
animation: draw 1s forwards;
}

@keyframes draw {
to {
stroke-dashoffset:  0;
}
}< /code>

Run Demo
Reset Demo

Ready to start



























User
// waiting…


Service Provider
// waiting…


Trusted Third Party
// waiting…





Подробнее здесь: https://stackoverflow.com/questions/797 ... ws-missing
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Html»