Creating 2-D Animations on Canvas - moving blade

In this tutorial, you will see the following:

  • How to turn a fan.
  • How to change its speed interactively.
  • How to turn the direction interactively.
Finding a good book to master HTML5 can be very challenging: there are so many around - most with eye-catching titles and very complex substance.
Therefore, Vivax Solutions strongly recommends Core HTML5 Canvas for those who really want to delve into HTML5.
Please click the image to access Amazon:

Interactive Moving Blade

In this example, several methods of context object are used to create a moving fan blade on canvas.

The fan blade is an image, placed at the centre of the canvas. Then, context.rotate() method can be used to rotate it by an argument given to the function in radians.

The angle must be given in radians.

Since there are eight blades in the image, the rotation angle is taken as 450 or π/4c to maximize the turning effect.

It uses new range element to manipulate the speed and a checkbox to determine the direction of motion - clockwise or anti-clockwise.



Speed:   Anti-clockwise





The Code for Interactive Fan is as follows:

<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
//declare the image object
var imgObj = new Image();
var b;
// translate the the top-left of the canvas to the centre
context.translate(200, 150);
// function to be called by the timer event
context.font = '14pt arial';
context.fillStyle = 'blue';
context.fillText('Press Start to Draw the Fan; then choose speed', -180, 0);
function fan() {
// clear canvas every 90 milisecond
context.clearRect(0, 0, 400, 300);
// get the speed
b = eval(document.getElementById('rang').value);
// rotate anti-clockwise
if (document.getElementById('chkdir').checked) { b = -b }
// rotate the canvas by multiple of (1/4)
context.rotate(b * Math.PI / 180);
context.drawImage(imgObj, -70, -70);
imgObj.src = "../images/rotor.jpg";
}
</script>

 

All Canvas Animations

 

 

 

Recommended Reading

Amazon Best Seller

 

Advertisements

Amazon Best Seller

Advertisement