This JavaScript Reference section displays the code for an example program that shows how to animate the shooting of a ball using scalable vector graphics (SVG).
<!DOCTYPE html> <html> <head> <title>XoaX.net's Javascript Shooting a Ball Animation</title> <script type="text/javascript" src="ShootingBall.js"></script> <button onclick="Restart()">Shoot</button> </head> <body> </body> </html>
const kiTotalTime = 150; var iTime = 0; var qPosition = { mdX:50.0, mdY:400.0}; var qInitVelocity = { mdX:3.3, mdY:10}; var gqTranslationSvg = null; var gbRunning = false; function UpdatePosition() { // Change the position and translation qPosition.mdX += qInitVelocity.mdX; qPosition.mdY -= (qInitVelocity.mdY - 20*(iTime/kiTotalTime)); gqTranslationSvg.setAttribute('transform', 'translate('+qPosition.mdX+', '+qPosition.mdY+')'); } function AnimationLoop() { UpdatePosition(); ++iTime; // Stop when the ball hits the ground if (qPosition.mdY < 400){ setTimeout(AnimationLoop, 25); } else { gbRunning = false; } } function Restart() { if (!gbRunning) { qPosition.mdX = 50.0; qPosition.mdY = 400.0; iTime = 0; gbRunning = true; AnimationLoop(); } } function Initialize() { qpBody = document.getElementsByTagName("body")[0]; // Create a 600 by 400 pixel region for drawing qMainDiv = document.createElement('div'); qpBody.appendChild(qMainDiv); qMainDiv.style.width = '600px'; qMainDiv.style.height = '400px'; qMainDiv.style.background = 'linear-gradient(cyan, tan)'; // The Main SVG Element var qMainSvg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); qMainSvg.style.width="600px"; qMainSvg.style.height="400px"; qMainDiv.appendChild(qMainSvg); // Add a SVG Translation Element gqTranslationSvg = document.createElementNS("http://www.w3.org/2000/svg", "g"); qMainSvg.appendChild(gqTranslationSvg); gqTranslationSvg.setAttribute('transform', 'translate('+qPosition.mdX+', '+qPosition.mdY+')'); // The SVG Ball Element var gqBallSvg = document.createElementNS("http://www.w3.org/2000/svg", "circle"); gqTranslationSvg.appendChild(gqBallSvg); gqBallSvg.setAttribute('cx', 0); gqBallSvg.setAttribute('cy', 0); gqBallSvg.setAttribute('r', 4); gqBallSvg.setAttribute('fill', 'rgb(55, 55, 55)'); } window.onload = Initialize;
© 20072024 XoaX.net LLC. All rights reserved.