Creating 2-D Animations on Canvas - animated candle

In this tutorial you will be able to:

  • Create a realistic-looking candle entirely from code without external images.
  • Light it up by using the mouse click event.
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:

Animated Candle

In this animation, the three main parts are wax, the wick and the flame.

The part of wax is produced by context.fillRect() method.

By using quadraticCurveTo() method, the flame is manipulated.

The wick is produced with context.fillRect() method.







The Source Code for Animated Candle is as follows:

<script>
var canvas = document.getElementById('Canvas_One');
var context = canvas.getContext('2d');
var a=0;var b=0.1;
// top of the candle
context.beginPath();
context.moveTo(190,150);
context.arc(200,150,22,0,Math.PI+0.1,false);
context.fillStyle='lightgrey';
context.fill();
// wax
context.beginPath()
context.moveTo(180,150);
context.rect(180,150,40,150);
context.fillStyle = 'lightgrey';
context.fill();
// the wick
context.beginPath();
context.moveTo(197,135);
context.fillStyle="black";
context.fill();
context.fillRect(197,135,5,15);
context.closePath();
function drawing(){
// for the movement of the flame
a=a+b;
if(a>=3){b=-0.1;}
if(a<=-3){b=0.1;}
// clear canvas
context.clearRect(0,0,400,300);
// top of the candle
context.beginPath();
context.moveTo(190,150);
context.arc(200,150,22,0,Math.PI+0.1,false);
context.fillStyle='lightgrey';
context.fill();
//yellow part of flame
context.beginPath();
context.moveTo(188,150);
context.quadraticCurveTo(200+a,18-a,212,150);
context.closePath();
context.fillStyle="#FFFE00";
context.fill();
//white part of flame
context.beginPath();
context.moveTo(193,150);
context.quadraticCurveTo(200+a,25-a,207,150);
context.closePath();
context.fillStyle="#E9DD00";
context.fill();
// blue part of flame
context.beginPath();
context.moveTo(194,150);
context.quadraticCurveTo(200+a,90+a,206,150);
context.fillStyle="rgba(0,0,255,0.8)";
context.fill();
// the wick
context.beginPath();
context.moveTo(197,135);
context.fillStyle="black";
context.fill();
context.fillRect(197,135,5,15);
context.closePath();
// wax
context.beginPath()
context.moveTo(180,150);
context.rect(180,150,40,150);
context.fillStyle = 'lightgrey';
context.fill();
}
</script>

 

All Canvas Animations