Prev Demo
Animation With Control Buttons In Javascript.
Next Demo
Write code here
J
|
B
|
A
<!DOCTYPE html> <html> <head> <title>Demo</title> </head> <body> <h1>Animation with control buttons.</h1> <style> #myId { width: 700px; background: none; padding: 1em; margin: 1em auto; } canvas { background: #ff6a00; } button { display:inline-flexbox; border-radius: 3px; border: 2px; font-size: 1.5rem; padding: 0.5rem 0.9em; background: #69c773; border-bottom: 1px solid #498b50; color: white; -webkit-font-smoothing: antialiased; font-weight: bold; margin: 0 0.30rem; text-align: center; } button:hover, button:focus { opacity: 0.9; cursor:pointer; } button:active { opacity: 1.2; box-shadow: 0 -4px 9px rgba(0, 0, 0, 0.5) inset; } </style> <div id="myId"> <div class="controls"> <button type="button" id="startBtn">Start Animation</button> <button type="button" id="stopBtn">Stop Animation</button> <button type="button" id="resetBtn">Reset</button> </div> <canvas id="stage" width="590" height="150"></canvas> </div> <script> (function() { var lastTime = 0; var vendors = ['ms', 'moz', 'webkit', 'o']; for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame']; window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame']; } if (!window.requestAnimationFrame) window.requestAnimationFrame = function(callback, element) { var currTime = new Date().getTime(); var timeToCall = Math.max(0, 16 - (currTime - lastTime)); var id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; if (!window.cancelAnimationFrame) window.cancelAnimationFrame = function(id) { clearTimeout(id); }; }()); (function() { var startBtn = document.getElementById('startBtn'); var stopBtn = document.getElementById('stopBtn'); var resetBtn = document.getElementById('resetBtn'); var requestID; var canvas = document.getElementById('stage'); var ctx = canvas.getContext('2d'); ctx.fillStyle = '#008080'; var posX = 0; var boxWidth = 50; var pixelsPerFrame = 5; ctx.fillRect(posX, 0, boxWidth, canvas.height); function animate() { requestID = requestAnimationFrame(animate); if (posX <= (canvas.width - boxWidth)) { ctx.clearRect((posX - pixelsPerFrame), 0, boxWidth, canvas.height); ctx.fillRect(posX, 0, boxWidth, canvas.height); posX += pixelsPerFrame; } else { cancelAnimationFrame(requestID); } } startBtn.addEventListener('click', function(e) { e.preventDefault(); requestID = requestAnimationFrame(animate); }); stopBtn.addEventListener('click', function(e) { e.preventDefault(); cancelAnimationFrame(requestID); }); resetBtn.addEventListener('click', function(e) { e.preventDefault(); posX = 0; ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.fillRect(posX, 0, boxWidth, canvas.height); }); }()); </script> </body> </html>
Note: We DO NOT save your trial code in our database.
Output