Comments: In this example, a beating flame is displayed on the screen using the canvas Element of HTML5 through Javascript, and the flame will follow the cursor
The complete code for this effect is as follows. You can view the effect by saving the code to an HTML file. The flame will follow the cursor:
The Code is as follows:
<! Doctype html>
<Head>
<Meta charset = UTF-8 "/>
<Title> HTML5 Canvas flame effect </title>
<Style type = "text/css">
Body {margin: 0; padding: 0 ;}
# Canvas-keleyi-com {display: block ;}
</Style>
</Head>
<Body>
<Canvas id = "canvas-keleyi-com"> </canvas>
<Script type = "text/javascript">
Window. onload = function (){
Var keleyi_canvas = document. getElementById ("canvas-kel" + "eyi-com ");
Var ctx = keleyi_canvas.getContext ("2d ");
Var W = window. innerWidth, H = window. innerHeight;
Keleyi_canvas.width = W;
Keleyi_canvas.height = H; </p> <p> var participant = [];
Var mouse ={}; </p> <p> // Lets create some participant now
Var participant _count = 100;
For (var I = 0; I <particle _count; I ++)
{
Participant. push (new particle ());
}
Keleyi_canvas.addEventListener ('mousemove ', track_mouse, false); </p> <p> function track_mouse (e)
{
Mouse. x = e. pageX;
Mouse. y = e. pageY;
} </P> <p> function particle ()
{
This. speed = {x:-2.5 + Math. random () * 5, y:-15 + Math. random () * 10 };
// Location = mouse coordinates
// Now the flame follows the mouse coordinates
If (mouse. x & mouse. y)
{
This. location = {x: mouse. x, y: mouse. y };
}
Else
{
This. location = {x: W/2, y: H/2 };
}
// Radius range = 10-30
This. radius = 10 + Math. random () * 20;
// Life range = 20-30
This. life = 20 + Math. random () * 10;
This. remaining_life = this. life;
// Colors
This. r = Math. round (Math. random () * 255 );
This. g = Math. round (Math. random () * 255 );
This. B = Math. round (Math. random () * 255 );
} </P> <p> function draw ()
{
Ctx. globalCompositeOperation = "source-over ";
Ctx. fillStyle = "black ";
Ctx. fillRect (0, 0, W, H );
Ctx. globalCompositeOperation = "lighter"; </p> <p> for (var I = 0; I <participant. length; I ++)
{
Var p = participant [I];
Ctx. beginPath ();
P. opacity = Math. round (p. remaining_life/p. life * 100)/100
Var gradient = ctx. createRadialGradient (p. location. x, p. location. y, 0, p. location. x, p. location. y, p. radius );
Gradient. addColorStop (0, "rgba (" + p. r + "," + p. g + "," + p. B + "," + p. opacity + ")");
Gradient. addColorStop (0.5, "rgba (" + p. r + "," + p. g + "," + p. B + "," + p. opacity + ")");
Gradient. addColorStop (1, "rgba (" + p. r + "," + p. g + "," + p. B + ", 0 )");
Ctx. fillStyle = gradient;
Ctx. arc (p. location. x, p. location. y, p. radius, Math. PI * 2, false );
Ctx. fill (); </p> <p>
P. remaining_life --;
P. radius --;
P. location. x + = p. speed. x;
P. location. y + = p. speed. y; </p> <p> if (p. remaining_life <0 | p. radius <0)
{
Particle [I] = new particle ();
}
}
} </P> <p> setInterval (draw, 86 );
}
</Script>
</Body>
</Html>