一:创建画布
<canvas width="600" height="600" id="canvas" style="border:1px solid red;"></canvas>
二:实现功能
var canvas = document.getElementById('canvas');
var cxt = canvas.getContext('2d');
var timer;
var iStop = false;
var fires = [];
function draw(){
var _fires = [];
for(var i=0; i<fires.length; i++){
cxt.save();
cxt.translate(fires[i].x, fires[i].y);
for(var j=0; j<12; j++){
cxt.save();
cxt.beginPath();
cxt.strokeStyle = 'rgba('+fires[i].color+', '+(fires[i].alpha--)/1000+')';
cxt.rotate(30*j*Math.PI/180+fires[i].offset);
cxt.translate(fires[i].radius++/10, 0);
cxt.rotate(45*Math.PI/180);
cxt.moveTo(0, 0);
cxt.lineTo(10, 0);
cxt.stroke();
cxt.closePath();
cxt.restore();
}
cxt.restore();
if(fires[i].alpha > 0){
_fires.push(fires[i])
}
}
fires = _fires;
}
function drawTip() {
cxt.save();
cxt.font="20px Verdana";
cxt.fillStyle = 'skyblue';
cxt.fillText('请单击页面!', 230, 290);
cxt.restore();
}
function erase(){
cxt.clearRect(0, 0, canvas.width, canvas.height);
}
canvas.onmousedown = function(e){
var ev = e || window.event;
var x = e.clientX - canvas.offsetLeft;
var y = e.clientY - canvas.offsetTop;
var r = Math.round(Math.random()*255);
var g = Math.round(Math.random()*255);
var b = Math.round(Math.random()*255);
var offset = Math.round(Math.random()*45);
fires.push({'radius':0,'alpha':1000,'x':x,'y':y,'color':r+','+g+','+b, 'offset':offset});
};
window.requestAnimationFrame =
window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame;
window.cancelRequestAnimationFrame =
window.cancelRequestAnimationFrame ||
window.mozCancelRequestAnimationFrame ||
window.webkitCancelRequestAnimationFrame ||
window.msCancelRequestAnimationFrame;
function animate() {
erase();
draw();
drawTip();
if(iStop){
cancelRequestAnimationFrame(timer);
}else{
timer = requestAnimationFrame(animate);
}
}
animate();