Introduction
In this article, we are going to understand Canvas Oscillation Animation Using HTML 5. In this section, you will see the animated cursor moving around just like a pendulum between the canvas while displaying in the browser.
Here we will use some JavaScript and some styles along with HTML code. Just go through the steps to see how to create this application.
Let's see how the OscillationAnimation application can be created. To do so use the following steps.
Step 1 : Open a HTML editor or Visual Studio.


- Go to Solution Explorer
- Right-click on the Application name
- Select Add-->add new item
- Now in the window that opens, select an HTML page or new Webform
- Rename it to OscillationAnimation.aspx

CSS Script
- <style>
- body
- {
- margin: 0px;
- padding: 0px;
- }
- Canvas
- {
- border: 2px solid #9C9898;
- margin-top: 50px;
- margin-left: 60px;
- background-color: #00B2EE;
- box-shadow: 5px 5px 8px #222;
- }
- .title
- {
- text-align: center;
- font-family: Segoe UI Light, Arial, Helvetica;
- font-size: 2.2em;
- margin: 1em;
- }
- .info
- {
- text-align: center;
- font-family: Segoe UI Light, Arial, Helvetica;
- font-size: 1.2em;
- margin: 0.25em;
- }
- </style>
Step 3: In this part, we need to work on some JavaScript. To fully understanding how the JavaScript works, download the attached .rar file and run the OscillationAnimation application.
The whole JavaScript looks as in the following:
- <script>
- window.requestAnimFrame = (function (callback)
- {
- return window.requestAnimationFrame ||
- window.webkitRequestAnimationFrame ||
- window.mozRequestAnimationFrame ||
- window.oRequestAnimationFrame ||
- window.msRequestAnimationFrame ||
- function (callback)
- {
- window.setTimeout(callback, 1000 / 60);
- };
- })();
- function animate(myRectangle)
- {
- var canvas = document.getElementById("myCanvas");
- var context = canvas.getContext("2d");
- // update
- var date = new Date();
- var time = date.getTime();
- var amplitude = 150;
- var period = 2000; // in ms
- var centerX = canvas.width / 2 - myRectangle.width / 2;
- var nextX = amplitude * Math.sin(time * 2 * Math.PI / period) + centerX;
- myRectangle.x = nextX;
- // clear
- context.clearRect(0, 0, canvas.width, canvas.height);
- // draw
- context.beginPath();
- context.rect(myRectangle.x, myRectangle.y, myRectangle.width, myRectangle.height);
- context.fillStyle = "#663366";
- context.fill();
- context.lineWidth = myRectangle.borderWidth;
- context.strokeStyle = "white";
- context.stroke();
- // request new frame
- requestAnimFrame(function ()
- {
- animate(myRectangle);
- });
- }
- window.onload = function ()
- {
- var myRectangle =
- {
- x: 250,
- y: 70,
- width: 100,
- height: 50,
- borderWidth: 5
- };
- animate(myRectangle);
- };
- </script>


Gowtham RajamanickamPosted Apr 11, 2015, 1:33 PM
good
Vijay PrativadiPosted Mar 13, 2012, 12:56 PM
Great Stuff Deepak...Keep Posting More!!!