HTML Canvas Animation with setInterval()
<!DOCTYPE HTML> <html> <head> <script> // SUMMARY: Draws a moving circle on a canvas. window.onload = function() {// w w w . j a v a 2 s .c om // CANVAS contexts. canvasC = document.getElementById("canvasCircle"); contextC = canvasC.getContext("2d"); canvasBG = document.getElementById("canvasBackground"); contextBG = canvasBG.getContext("2d"); // PARAMETERS. let xPos = 50; let yPos = canvasC.height / 2; let radius = 40; let endXPos = canvasC.width - 75; let change = 10; let startAngle = (Math.PI / 180) * 0; let interval = 80; let endAngle = (Math.PI / 180) * 360; // BACKGROUND canvas filled with color. contextBG.fillStyle = "silver"; contextBG.fillRect(0, 0, canvasBG.width, canvasBG.height); // INTERVAL for drawing let intervalID = setInterval(drawCircle, interval); // DRAW CIRCLE function. function drawCircle() { // CLEAR canvas for each image. //contextC.clearRect(0,0,canvasC.width,canvasC.height); // ATTRIBUTES of the circle. contextC.strokeStyle = "red"; contextC.lineWidth = 4; contextC.shadowOffsetX = 3; contextC.shadowOffsetY = 3; contextC.shadowBlur = 5; contextC.shadowColor = "gray"; // POSITION change. xPos += change; // STOP if reached end. if (xPos > endXPos) { clearInterval(intervalID); } // DRAW circle. contextC.beginPath(); contextC.arc(xPos, yPos, radius, startAngle, endAngle, true); contextC.stroke(); } } </script> </head> <body> <div> <canvas id="canvasCircle" width="400" height="125" style="border: 2px solid black; position: absolute; left: auto; top: auto; z-index: 2"> You're browser doesn't currently support HTML5 Canvas. </canvas> <canvas id="canvasBackground" width="400" height="125" style="border: 2px solid black; position: absolute; left: auto; top: auto; z-index: 1"> You're browser doesn't currently support HTML5 Canvas. </canvas> </div> </body> </html>