本效果的完整程式碼如下,把程式碼儲存到HTML檔案中開啟也能查看效果,火焰會跟著遊標: 複製程式碼複製程式碼 程式碼如下: HTML5 Canvas火焰效果 <br />body{margin: 0; padding: 0;}<br />#canvas-keleyi-com {display: block;}<br /> <br />window.onload = function(){<br />var keleyi_canvas = document.getElementById("canvas-kel" "eyi-com");<br />var ctx = keleyi_canvas.getContext("2d")<br />var W = window.innerWidth, H = window.innerHeight;<br />keleyi_canvas.width = W;<br />keleyi_canvas.height = H; <p>var particles = [];<br />var mouse = {}; <p>//Lets create some particles now<br />var particle_count = 100;<br />for(var i = 0; i < particle_count; i )<br />{<br />particles.pushicle_count; i )<br />{<>particles.push(new particle() ;<br />}<br />keleyi_canvas.addEventListener('mousemove', track_mouse, false); <p>function track_mouse(e)<br />{<br />mouse.x = e.pageX;<br />mouse.y = e.pageY;<br />} <p>function particle()<br />{<br />this.speed = {x: -2.5 Math.random()*5, y: -15 Math.random()*10};<br />//location = mouse coordinates<br />//Now the flame follows the mouse coordinates<br />if(mouse.x && mouse.y)<br />{<br />this.location = {x: mouse.x, yy: mo. y};<br />}<br />else<br />{<br />this.location = {x: W/2, y: H/2};<br />}<br />//radius range = 10- 30<br />this.radius = 10 Math.random()*20;<br />//life range = 20-30<br />this.life = 20 Math.random()*10;<br />this.remaining_life = this.life;<br />//colors<br />this.r = Math.round(Math.random()*255);<br />this.g = Math.round(Math.random()*255) ;<br />this.b = Math.round(Math.random()*255);<br />} <p>function draw()<br />{<br />ctx.globalCompositeOperation = "source-over";<br />ctx.fillStyle = "black";<br />ctx.fillRect(0, 0, W, H) ;<br />ctx.globalCompositeOperation = "lighter"; <p>for(var i = 0; i < particles.length; i )<br />{<br />var p = particles[i];<br />ctx.beginPath();<br />p.opacity = Math .round(p.remaining_life/p.life*100)/100<br />var gradient = ctx.createRadialGradient(p.location.x, p.location.y, 0, p.location.x, p.location.y , p.radius);<br />gradient.addColorStop(0, "rgba(" p.r ", " p.g ", " p.b ", " p.opacity ")");<br />gradient.addColorStop(0.5, "rgba (" p.r ", " p.g ", " p.b ", " p.opacity ")");<br />gradient.addColorStop(1, "rgba(" p.r ", " p.g ", " p.b ", 0)") ;<br />ctx.fillStyle = gradient;<br />ctx.arc(p.location.x, p.location.y, p.radius, Math.PI*2, false);<br />ctx.fill() ; <p><br />p.remaining_life--;<br />p.radius--;<br />p.location.x = p.speed.x;<br />p.location.y = p.speed.y ; <p>if(p.remaining_life < 0 || p.radius < 0)<br />{<br />particles[i] = new particle();<br />}<br />}<br />} <p>setInterval(draw, 86); }