html5使用canvas实现跟随光标跳动的火焰效果

2022-10-20,,,,

效果的完整代码如下,把代码保存到html文件中打开也能查看效果,火焰跟随光标:

复制代码代码如下:
<!doctype html>
<head>
<meta charset=utf-8" />
<title>html5 canvas火焰效果</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 particles = [];
var mouse = {};</p>
<p>//lets create some particles now
var particle_count = 100;
for(var i = 0; i < particle_count; i++)
{
particles.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 < particles.length; i++)
{
var p = particles[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)
{
particles[i] = new particle();
}
}
}</p>
<p>setinterval(draw, 86);
}
</script>
</body>
</html>

《html5使用canvas实现跟随光标跳动的火焰效果.doc》

下载本文的Word格式文档,以方便收藏与打印。