Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <body>
- <h1>Q3 Animation - SET 3</h1>
- <h3>Q1. Write the code using Canvas API for circles and <i>RequestAnimationFrame</i> to create the following animation.
- [10 marks]<h3>
- <p align="center">Note that red and black balls start from center at the bottom and move towards the opposite corners.
- When they reach the corner they fall back again towards their starting position at the bottom center and then the animation
- continues as before. Note that the animation is continuous.</p>
- <div align="center">
- <img src = "set3q3.gif">
- </div>
- <hr />
- <p></p>
- <div align="center">
- <canvas id="canvas1" width="400" height="200" tabindex="0" style=";border:1px solid #000000;">
- </canvas>
- </div>
- <script>
- var canvas = document.getElementById("canvas1");
- var ctx = canvas.getContext("2d");
- //get the animation frame depending on the browser engine
- var requestAnimationFrame = window.requestAnimationFrame ||
- window.mozRequestAnimationFrame ||
- window.webkitRequestAnimationFrame ||
- window.msRequestAnimationFrame;
- //set intial start x and y coordinates
- var redX = canvas.width / 2;
- var redY = canvas.height;
- var redBallGoingUp = true;
- var radius = 10;
- var delayBetweenFrames = 20; //the delay time is in milliseconds
- //declare the animate() function
- function animate() {
- //use the setTimeout to do the animation between frame using the delayBetweenFrames
- setTimeout(function() {
- //animation code goes into this anonymous function handler
- requestAnimationFrame(animate);
- //clear the whole canvas area
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- if (redBallGoingUp) {
- redX = redX - 5;
- redY = redY - 5;
- }
- if (!redBallGoingUp) {
- redX = redX + 5;
- redY = redY + 5;
- }
- drawCircle(redX, redY, 10, "red");
- if (redY == 0) {
- redBallGoingUp = false;
- }
- if (!redBallGoingUp && redY == canvas.height) {
- redBallGoingUp = true;
- }
- }, delayBetweenFrames);
- }
- function drawCircle(x, y, radius, color) {
- //draw a circle
- ctx.beginPath();
- ctx.arc(x, y, radius, 0, 2 * Math.PI);
- //fill the circle with green color
- ctx.fillStyle = color;
- ctx.fill();
- }
- //call the animate() function
- animate();
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement