Simple Animation using Canvas: HTML5

Today lets see how we can do simple animation using Canvas.

moving-circle-animation-canvas-html5

Demo

Here we draw a circle and move it from starting point of x-axis to the end of the canvas.

index.html and myStyle.css file content are same as Linear Gradients in Canvas: HTML5

JavaScript file: Moving Circle Code
myScript.js

1
2
3
4
context.beginPath();
context.fillStyle = "red";
context.arc(x++, context.canvas.height/2, r, 0, 2 * Math.PI);
context.fill();

Here I’m drawing a circle with a red fill and incrementing it’s x-axis value each time it is called.

JavaScript file: x-axis movement control
myScript.js

1
2
3
4
5
var r = 50;
var x = -r;
 
if( x >= context.canvas.width + r)
    x  = -r;

Here the x-axis value is tracked each time and is set back to -50 ( minus radius of the circle ) once the circle moves out of the x-axis or the canvas width.

Simple Animation using Canvas: HTML5


[youtube https://www.youtube.com/watch?v=iyGQhumPgcc]

YouTube Link: https://www.youtube.com/watch?v=iyGQhumPgcc [Watch the Video In Full Screen.]



JavaScript file: Full Free Source Code
myScript.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
window.onload = canvas;
 
function canvas()
{
var myCanvas = document.getElementById("myCanvas");
 
if( myCanvas && myCanvas.getContext("2d") ) 
{
var context         = myCanvas.getContext("2d");
var r = 50;
var x = -r;
 
setInterval(function(){
context.fillStyle   = "#000";
context.fillRect(0, 0, context.canvas.width, context.canvas.height);
 
context.beginPath();
context.fillStyle   = "red";
context.arc(x++, context.canvas.height/2, r, 0, 2 * Math.PI);
context.fill();
 
if( x >= context.canvas.width + r)
    x  = -r; 
}, 10);
}
}

Here we use the setInterval() method to iterate/loop through the anonymous function and each time the background of the canvas is set to black(#000 or #000000) by drawing a black rectangle across the entire canvas width and height. For every call the value of x increments by 1, hence the circle moves 1px away from its previous position, until it reaches the end of canvas – after which it is reset back to -r value.

Custom Transformation in Canvas: HTML5

Today lets learn how to apply custom transformation to our drawings on canvas.

custom transformation canvas html5

In this video tutorial, we draw 3 rectangles and show you how scale, skew and move properties of custom transform methods work.

Custom Transformation Methods
transform(a, b, c, d, e, f);
setTransform(a, b, c, d, e, f);

custom transformation matrix canvas html5

Custom transformation takes the form of a square matrix, as shown above.

a – Scales drawing horizontally
b – Skews drawing horizontally
c – Skews drawing vertically
d – Scales drawing vertically
e – Moves drawing horizontally
f – Moves drawing vertically

Recommended Read:
Translate Transformation in Canvas: HTML5
Scale Transformation in Canvas: HTML5
Rotate Transformation in Canvas: HTML5

index.html and myStyle.css file content are same as Linear Gradients in Canvas: HTML5

JavaScript file: Transform method
myScript.js

1
2
3
4
5
6
7
context.fillStyle = "blue";
context.fillRect(5, 5, 150, 75);
 
context.transform(1, 0.5, 0.5, 1, 10, 10);
 
context.fillStyle = "red";
context.fillRect(5, 5, 150, 75);

transform() method changes the origin of the canvas to (x, y) = (10, 10) and scale horizontally and vertically, so that we can see it drawn on the canvas. Also skews by 0.5 both horizontally and vertically.

JavaScript file: Transform method is Additive
myScript.js

1
2
3
4
5
6
7
8
9
10
11
12
context.fillStyle = "blue";
context.fillRect(5, 5, 150, 75);
 
context.transform(1, 0.5, 0.5, 1, 10, 10);
 
context.fillStyle = "red";
context.fillRect(5, 5, 150, 75);
 
context.transform(1, 0, 0, 1, 20, 200);
 
context.fillStyle = "gray";
context.fillRect(5, 5, 150, 75);

Using transform() method we draw third rectangle at (x, y) = (20, 200); And horizontal and vertical skew is made 0, but still a skew of 0.5 is applied both in horizontal and vertical direction, since the transform() method written before for second rectangle is influencing it.

JavaScript file: setTransform method is not Additive
myScript.js

1
2
3
4
5
6
7
8
9
10
11
12
context.fillStyle = "blue";
context.fillRect(5, 5, 150, 75);
 
context.transform(1, 0.5, 0.5, 1, 10, 10);
 
context.fillStyle = "red";
context.fillRect(5, 5, 150, 75);
 
context.setTransform(1, -0.5, 0, 1, 20, 200);
 
context.fillStyle = "gray";
context.fillRect(5, 5, 150, 75);

setTransform() method is non-additive in nature. It is independent of its previous transformation matrix. All other parameter and behavior are same with respect to transform() and setTransform() methods.

Custom Transformation in Canvas: HTML5


[youtube https://www.youtube.com/watch?v=9eyr9MQNAuM]

YouTube Link: https://www.youtube.com/watch?v=9eyr9MQNAuM [Watch the Video In Full Screen.]



JavaScript file: Full Free Code
myScript.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
window.onload = canvas;
 
function canvas()
{
var myCanvas = document.getElementById("myCanvas");
 
if( myCanvas && myCanvas.getContext("2d") ) 
{
var context         = myCanvas.getContext("2d");
 
context.fillStyle   = "blue";
context.fillRect(5, 5, 150, 75);
 
context.transform(1, 0.5, 0.5, 1, 10, 10);
 
context.fillStyle   = "red";
context.fillRect(5, 5, 150, 75);
 
context.setTransform(1, -0.5, 0, 1, 20, 200);
 
context.fillStyle   = "gray";
context.fillRect(5, 5, 150, 75);
}
}

Skewing can be done both in positive and negative direction, as shown in the video. If you previously used scale() and/or rotate() transformations that will be additive to transform() method, and will have no influence on setTransform() method.

Moving Image Inside HTML page: Javascript ( A Small Fun Application )

Write a xHTML program to take input from the user and move the image to the corresponding location(position), using Javascript.

Note: ( CSS – Cascading StyleSheet )
Static Positioning does not have top and left properties, so an image which is positioned as Static can’t be moved.
Absolute positioning: The image moves to the new location according to the values of top and left.
Relative positioning: Here the image moves relative to its original position. From its original position, it applies the new top and left value and moves accordingly.

Video Explaining The Code:



YouTube Link: https://www.youtube.com/watch?v=cJtMtd2QmMM [Watch the Video In Full Screen.]



Write a xhtml program, and use the form input tags and accept two values from the user. Using document.getElementById, get those user entered values and assign it to two variables.
Similarly, using the div tags id, change the style information and assign the user entered values to div tags top and left position whenever user hits the “move” button.

Source Code: (move.html)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
 
<html>
 <head><title> Move Image </title>
 
 <style type="text/css">
  #kids { position: relative; top: 200px; left: 400px; }
 </style>
 
 <script type="text/javascript">
 
  function moveIt()
 {
var x = document.getElementById("x").value;
var y = document.getElementById("y").value;
 
var kids = document.getElementById("kids").style;
 
kids.top = x + "px";
kids.left = y  + "px";
 
 }
 
 </script>
 </head>
 <body>
 
<form>
X axis: <input type="text" id="x"><br />
Y axis: <input type="text" id="y"><br />
<input type="button" value=" Move " onclick="moveIt()" >
</form>
 
<div id="kids">
  <img 
  src="http://technotip.org/wp-content/themes/NewsDen/images/logo.gif" 
  width="220" height="42">
</div>
 
 </body>
</html>

Fun Application Code:
We have made some minor changes to the above code to get the x and y co-ordinates from the cursor position automatically.

Here, we do not accept input directly from the user. We have removed the html form using html comments(

<!--  Comments -->

) and invoke the javascript function moveIt when the user moves his mouse on the html document.
When there is onmousemove event, most browsers automatically throw some objects and we accept it in our function(as parameter) and make use of it. Some browsers like Microsoft’s Internet Explorer do not throw the event object automatically, so we assign it manually using the below code

   if( !evnt )
evnt = window.event;

Explanation of above two lines of code:
If evnt does not exist, then assign the event to evnt variable.

Also Make Sure To Watch This Video: Event Object: Javascript

Now using the clientX and clientY or screenX and screenY property of the event object, we track the x and y co-ordinates of the cursor and assign that value to the top and left position of the image(div tag which wraps the image tag).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
 
<html>
 <head><title> Move Image </title>
 
 <style type="text/css">
  #kids { position: relative; top: 200px; left: 400px; }
#x, #y { font-size: 24pt; color: red; }
 </style>
 
 <script type="text/javascript">
 
document.onmousemove = moveIt;
 
  function moveIt(evnt)
 {
if( !evnt )
evnt = window.event;
 
var x = evnt.clientX;
var y = evnt.clientY;
 
var kids = document.getElementById("kids").style;
 
kids.top = x + "px";
kids.left = y  + "px";
 
document.getElementById("x").innerHTML = x;
document.getElementById("y").innerHTML = y;
 
 
 }
 
 </script>
 </head>
 <body>
X:<span id="x"></span><br />
Y:<span id="y"></span>
<!--
<form>
X axis: <input type="text" id="x"><br />
Y axis: <input type="text" id="y"><br />
<input type="button" value=" Move " onclick="moveIt()" >
</form>
-->
<div id="kids">
 <img 
 src="http://technotip.org/wp-content/themes/NewsDen/images/logo.gif" 
 width="220" height="42">
</div>
 
 </body>
</html>

Hence, whenever the user move his mouse pointer over the html document the image starts moving according to the new value generated for the each move.