Trước đây cũng đã có bài hướng dẫn cách tạo pháo hoa cho blogspot Tại đây. Nhưng nó không hoành tráng như những hiệu ứng pháo hoa sắp chia sẻ ngay sau đây.
Tổng hợp hiệu ứng pháo hoa đẹp đến không ngờ cho blogspot.
1- Hiệu ứng pháo hoa 1Demo trên codepen
DEMO
Demo trên blogspot
DEMO
CÀI ĐẶT
Bước 1:
Thêm đoạn HTML vào ngay sau <body>
<canvas height='900' id='canvas' style='position:fixed;width:100%;pointer-events:none;z-index:9999;' width='1440'/>Bước 2:
Thêm javascript sau vào trước </body>
<script type='text/javascript'>
//<![CDATA[
window.onload = function(){
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
cw = window.innerWidth,
ch = window.innerHeight,
fireworks = [],
particles = [],
hue = 120,
limiterTotal = 20,
limiterTick = 0,
timerTotal = 30,
randomTime = 0,
timerTick = 0,
mousedown = false,
mx,
my;
canvas.width = cw;
canvas.height = ch;
//$('canvas').css("background-size":cw);
// var snd = new Audio("http://soundjax.com/reddo/38563%5EFirework.mp3"); // buffers automatically when created
var snd = new Audio("http://soundjax.com/reddo/51715%5Efirework.mp3");
// now we are going to setup our function placeholders for the entire demo
// get a random number within a range
function random( min, max ) {
return min + Math.random()*(max-min);
}
// calculate the distance between two points
function calculateDistance( p1x, p1y, p2x, p2y ) {
return Math.sqrt((p1x-p2x)*(p1x-p2x) + (p1y-p2y)*(p1y-p2y));
}
// create firework
function Firework( sx, sy, tx, ty ) {
//actual coordinates
this.x = sx;
this.y = sy;
//starting coordinate
this.sx = sx;
this.sy = sy;
//target coordinates
this.tx = tx;
this.ty = ty;
this.distanceToTarget = calculateDistance(sx, sy, tx, ty);
this.distanceTraveled = 0;
//track past coordinates to creates a trail effect
this.coordinates = [];
this.coordinateCount = 2;
while(this.coordinateCount--) {
this.coordinates.push( [this.x, this.y ]);
}
this.angle = Math.atan2(ty - sy, tx - sx);
this.speed = 1;
this.acceleration = 1.2;
this.brightness = random(50, 70);
this.tragetRadius = 1;
}
// update firework
Firework.prototype.update = function( index ) {
// if(this.distanceTraveled >= this.distanceToTarget ){
// fireworks.splice(index, 1);
// }
if( this.targetRadius < 8){
this.targetRadius += 0.3;
}else{
this.targetRadius = 1;
}
this.speed *= this.acceleration;
var vx = Math.cos(this.angle)*this.speed,
vy = Math.sin(this.angle)*this.speed;
this.distanceTraveled = calculateDistance(this.sx, this.sy, this.x + vx, this.y + vy);
if(this.distanceTraveled >= this.distanceToTarget ){
this.coordinates.pop();
this.coordinates.unshift([this.tx, this.ty]);
//this.x = this.tx; this.y = this.ty;
createParticles(this.x, this.y);
snd.play();
this.draw();
fireworks.splice(index, 1);
} else {
this.x += vx;
this.y += vy;
}
this.coordinates.pop();
this.coordinates.unshift([this.x, this.y]);
};
// draw firework
Firework.prototype.draw = function() {
ctx.beginPath();
// move to the last tracked coordinate in the set, then draw a line to the current x and y
ctx.moveTo( this.coordinates[ this.coordinates.length - 1][ 0 ], this.coordinates[ this.coordinates.length - 1][ 1 ] );
ctx.lineTo( this.x, this.y );
ctx.strokeStyle = 'hsl(' + hue + ', 100%, ' + this.brightness + '%)';
ctx.stroke();
// ctx.beginPath();
// ctx.arc(this.tx, this.ty, this.targetRadius, 0, Math.PI*2);
// ctx.stroke();
}
// create particle
function Particle( x, y, type ) {
this.x = x;
this.y = y;
this.type = type;
// track the past coordinates of each particle to create a trail effect, increase the coordinate count to create more prominent trails
this.coordinates = [];
this.coordinateCount = 6;
while( this.coordinateCount-- ) {
this.coordinates.push( [ this.x, this.y ] );
}
// TO Be Improved //
switch (type)
{
case 1: var variation = random(1, 5);
if (variation < 2)
{
// set a random angle in all possible directions, in radians
this.angle = random( 0, Math.PI * 2 );
this.speed = random( 1, 15 );
// friction will slow the particle down
this.friction = 0.95;
// gravity will be applied and pull the particle down
this.gravity = 4;
// set the hue to a random number +-20 of the overall hue variable
this.hue = random( hue - 50, hue + 50 );
this.brightness = random( 50, 80 );
this.alpha = 1;
// set how fast the particle fades out
this.decay = random( 0.01, 0.02 );
}else if (variation < 3)
{
// set a random angle in all possible directions, in radians
this.angle = random( 0, Math.PI * 2 );
this.speed = random( 1, 5 );
// friction will slow the particle down
this.friction = 0.95;
// gravity will be applied and pull the particle down
this.gravity = 3;
// set the hue to a random number +-20 of the overall hue variable
this.hue = random( hue - 50, hue );
this.brightness = random( 50, 80 );
this.alpha = 1;
// set how fast the particle fades out
this.decay = random( 0.015, 0.03 );
}else if (variation < 4)
{
// set a random angle in all possible directions, in radians
this.angle = random( 0, Math.PI * 2 );
this.speed = random( 1, 8 );
// friction will slow the particle down
this.friction = 0.95;
// gravity will be applied and pull the particle down
this.gravity = 3;
// set the hue to a random number +-20 of the overall hue variable
this.hue = random( hue, hue + 50 );
this.brightness = random( 50, 80 );
this.alpha = 1;
// set how fast the particle fades out
this.decay = random( 0.015, 0.03 );
}else
{
// set a random angle in all possible directions, in radians
this.angle = random( 0, Math.PI * 2 );
this.speed = random( 1, 15 );
// friction will slow the particle down
this.friction = 0.95;
// gravity will be applied and pull the particle down
this.gravity = 3;
// set the hue to a random number +-20 of the overall hue variable
this.hue = random( hue - 50, hue + 50 );
this.brightness = random( 10, 20 );
this.alpha = 1;
// set how fast the particle fades out
this.decay = random( 0.015, 0.3 );
}
break;
case 2: var variation = random(1, 5);
if (variation < 2)
{
// set a random angle in all possible directions, in radians
this.angle = random( 0, Math.PI * 2 );
this.speed = random( 1, 10 );
// friction will slow the particle down
this.friction = 0.95;
// gravity will be applied and pull the particle down
this.gravity = 4;
// set the hue to a random number +-20 of the overall hue variable
this.hue = 100;
this.brightness = random( 50, 80 );
this.alpha = 1;
// set how fast the particle fades out
this.decay = random( 0.01, 0.02 );
}else if (variation < 3)
{
// set a random angle in all possible directions, in radians
this.angle = random( 0, Math.PI * 2 );
this.speed = random( 1, 21 );
// friction will slow the particle down
this.friction = 0.95;
// gravity will be applied and pull the particle down
this.gravity = 3;
// set the hue to a random number +-20 of the overall hue variable
this.hue = 100;
this.brightness = random( 50, 80 );
this.alpha = 1;
// set how fast the particle fades out
this.decay = random( 0.015, 0.03 );
}else if (variation < 4)
{
// set a random angle in all possible directions, in radians
this.angle = random( 0, Math.PI * 2 );
this.speed = random( 1, 3 );
// friction will slow the particle down
this.friction = 0.95;
// gravity will be applied and pull the particle down
this.gravity = 3;
// set the hue to a random number +-20 of the overall hue variable
this.hue = 100;
this.brightness = random( 50, 80 );
this.alpha = 1;
// set how fast the particle fades out
this.decay = random( 0.015, 0.03 );
}else
{
// set a random angle in all possible directions, in radians
this.angle = random( 0, Math.PI * 2 );
this.speed = random( 1, 5 );
// friction will slow the particle down
this.friction = 0.95;
// gravity will be applied and pull the particle down
this.gravity = 3;
// set the hue to a random number +-20 of the othis.hue = 100;
this.hue = 100;
this.brightness = random( 10, 20 );
this.alpha = 1;
// set how fast the particle fades out
this.decay = random( 0.015, 0.3 );
}
break;
case 3: var variation = random(1, 5);
// var hue = 10;
if (variation < 2)
{
// set a random angle in all possible directions, in radians
this.angle = random( 0, Math.PI * 2 );
this.speed = random( 10, 15 );
// friction will slow the particle down
this.friction = 0.95;
// gravity will be applied and pull the particle down
this.gravity = 4;
// set the hue to a random number +-20 of the overall hue variable
this.hue = 60;
this.brightness = random( 10, 20 );
this.alpha = 1;
// set how fast the particle fades out
this.decay = random( 0.01, 0.02 );
}else if (variation < 3)
{
// set a random angle in all possible directions, in radians
this.angle = random( 0, Math.PI * 2 );
this.speed = random( 11, 15 );
// friction will slow the particle down
this.friction = 0.95;
// gravity will be applied and pull the particle down
this.gravity = 3;
// set the hue to a random number +-20 of the overall hue variable
this.hue = 10;
this.brightness = random( 10, 20);
this.alpha = 1;
// set how fast the particle fades out
this.decay = random( 0.015, 0.03 );
}else if (variation < 4)
{
// set a random angle in all possible directions, in radians
this.angle = random( 0, Math.PI * 2 );
this.speed = random( 11, 18 );
// friction will slow the particle down
this.friction = 0.95;
// gravity will be applied and pull the particle down
this.gravity = 3;
// set the hue to a random number +-20 of the overall hue variable
this.hue = 90;
this.brightness = random( 10, 20 );
this.alpha = 1;
// set how fast the particle fades out
this.decay = random( 0.015, 0.03 );
}else
{
// set a random angle in all possible directions, in radians
this.angle = random( 0, Math.PI * 2 );
this.speed = random( 11, 15 );
// friction will slow the particle down
this.friction = 0.95;
// gravity will be applied and pull the particle down
this.gravity = 3;
// set the hue to a random number +-20 of the overall hue variable
this.hue = 120;
this.brightness = random( 10, 20 );
this.alpha = 1;
// set how fast the particle fades out
this.decay = random( 0.015, 0.3 );
}
break;
case 4: var variation = random(1, 5);
if (variation < 2)
{
// set a random angle in all possible directions, in radians
this.angle = random( 0, Math.PI * 2 );
this.speed = random( 1, 10 );
// friction will slow the particle down
this.friction = 0.95;
// gravity will be applied and pull the particle down
this.gravity = 4;
// set the hue to a random number +-20 of the overall hue variable
this.hue = 300;
this.brightness = random( 50, 80 );
this.alpha = 1;
// set how fast the particle fades out
this.decay = random( 0.01, 0.02 );
}else if (variation < 3)
{
// set a random angle in all possible directions, in radians
this.angle = random( 0, Math.PI * 2 );
this.speed = random( 1, 21 );
// friction will slow the particle down
this.friction = 0.95;
// gravity will be applied and pull the particle down
this.gravity = 3;
// set the hue to a random number +-20 of the overall hue variable
this.hue = 300;
this.brightness = random( 50, 80 );
this.alpha = 1;
// set how fast the particle fades out
this.decay = random( 0.015, 0.03 );
}else if (variation < 4)
{
// set a random angle in all possible directions, in radians
this.angle = random( 0, Math.PI * 2 );
this.speed = random( 1, 3 );
// friction will slow the particle down
this.friction = 0.95;
// gravity will be applied and pull the particle down
this.gravity = 3;
// set the hue to a random number +-20 of the overall hue variable
this.hue = 300;
this.brightness = random( 50, 80 );
this.alpha = 1;
// set how fast the particle fades out
this.decay = random( 0.015, 0.03 );
}else
{
// set a random angle in all possible directions, in radians
this.angle = random( 0, Math.PI * 2 );
this.speed = random( 1, 5 );
// friction will slow the particle down
this.friction = 0.95;
// gravity will be applied and pull the particle down
this.gravity = 3;
// set the hue to a random number +-20 of the othis.hue = 100;
this.hue = 100;
this.brightness = random( 10, 20 );
this.alpha = 1;
// set how fast the particle fades out
this.decay = random( 0.015, 0.3 );
}
break;
default:
}
}
// update particle
Particle.prototype.update = function( index ) {
// slow down the particle
this.speed *= this.friction;
// apply velocity
this.x += Math.cos( this.angle ) * this.speed;
this.y += Math.sin( this.angle ) * this.speed + this.gravity;
// fade out the particle
// this.alpha -= this.decay * this.alpha;
this.alpha -= this.decay;
if (this.type == 4 && this.alpha <= 0.5){
this.brightness += 50;
this.hue += 200;
if (this.brightness >= 200)
this.brightness = 0;
}
// remove the particle once the alpha is low enough, based on the passed in index
if( this.alpha <= this.decay ) {
particles.splice( index, 1 );
}
// remove last item in coordinates array
this.coordinates.pop();
// add current coordinates to the start of the array
this.coordinates.unshift( [ this.x, this.y ] );
}
// draw particle
Particle.prototype.draw = function() {
ctx. beginPath();
// move to the last tracked coordinates in the set, then draw a line to the current x and y
ctx.moveTo( this.coordinates[ this.coordinates.length - 1 ][ 0 ], this.coordinates[ this.coordinates.length - 1 ][ 1 ] );
ctx.lineTo( this.x, this.y );
ctx.strokeStyle = 'hsla(' + this.hue + ', 100%, ' + this.brightness + '%, ' + this.alpha + ')';
ctx.stroke();
}
// create particle group/explosion
function createParticles( x, y ) {
var particleCount = 300;
var type = Math.floor(random(1, 5));
while(particleCount--){
particles.push(new Particle(x, y, type));
}
}
// main demo loop
function loop() {
//requestAnimFrame(loop);
hue += 0.5;
ctx.globalCompositeOperation = "destination-out";
ctx.fillStyle = 'rgba(0, 0, 0, 0.3)';
ctx.fillRect(0, 0, cw, ch);
ctx.globalCompositeOperation = "lighter";
var i = fireworks.length;
while(i--)
{
fireworks[i].draw();
fireworks[i].update(i);
}
// loop over each particle, draw it, update it
var i = particles.length;
while( i-- ) {
particles[ i ].draw();
particles[ i ].update( i );
}
if( timerTick >= timerTotal + randomTime ){
if (!mousedown){
/* uniform */
// fireworks.push( new Firework(cw/2, ch, 100, random(0, ch/2)));
/* 0 to cw/2, more to*/
// fireworks.push( new Firework(cw/2, ch, Math.floor(Math.sqrt(random(0, cw*cw/4))), random(0, ch/2)));
var xPos = Math.pow(Math.floor((random(-Math.pow(cw/2, 1/3), Math.pow(cw/2, 1/3)))), 3);
xPos += cw/2;
fireworks.push( new Firework(cw/2, ch, xPos, random(0, ch/2)));
// fireworks.push( new Firework(cw/2, ch, random(-10, 100), random(0, ch/2)));
timerTick = 0;
randomTime = Math.pow(random(2, 4), 2);
}
} else {
timerTick++;
}
// limit the rate at which fireworks get launched when mouse is down
if( limiterTick >= limiterTotal ) {
if( mousedown ) {
// start the firework at the bottom middle of the screen, then set the current mouse coordinates as the target
fireworks.push( new Firework( cw / 2, ch, mx, my ) );
limiterTick = 0;
} else {
limiterTick= limiterTotal;
}
} else {
limiterTick++;
}
}
// mouse event bindings
// update the mouse coordinates on mousemove
canvas.addEventListener( 'mousemove', function( e ) {
mx = e.pageX - canvas.offsetLeft;
my = e.pageY - canvas.offsetTop;
});
// toggle mousedown state and prevent canvas from being selected
canvas.addEventListener( 'mousedown', function( e ) {
e.preventDefault();
mousedown = true;
});
canvas.addEventListener( 'mouseup', function( e ) {
e.preventDefault();
mousedown = false;
});
setInterval(loop, 25);
// (function game(){
// loop();
// setTimeout(game, Math.floor(random(30, 30)));
// })();
};
//]]>
</script>Chỉnh mật độ pháo hoa ở trị số timerTotal = 30,
Càng nhỏ càng ào ạt.
2- Hiệu ứng pháo hoa 2
Hiệu ứng này phù hợp với blogspot có nền tối vì pháo hoa không sặc sỡ.Và lưu ý blog của bạn cần có thư viện jquery
Demo trên codepen
DEMO
CÀI ĐẶT
Bước 1:
Bước này thực hiện như bước 1 của hiệu ứng 1
Bước 2:
Thêm javascript sau vào trước </body>
<script type='text/javascript'>
//<![CDATA[
const PARTICLES_PER_FIREWORK = 150; // 100 - 400 or try 1000
const FIREWORK_CHANCE = 0.02; // percentage, set to 0 and click instead
const BASE_PARTICLE_SPEED = 0.6; // between 0-4, controls the size of the overall fireworks
const FIREWORK_LIFESPAN = 600; // ms
const PARTICLE_INITIAL_SPEED = 4.5; // 2-8
// not so fun options =\
const GRAVITY = 9.8;
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let particles = [];
let disableAutoFireworks = false;
let resetDisable = 0;
let loop = () => {
if (!disableAutoFireworks && Math.random() < FIREWORK_CHANCE) {
createFirework();
}
ctx.clearRect(0, 0, canvas.width, canvas.height);
particles.forEach((particle, i) => {
particle.animate();
particle.render();
if (particle.y > canvas.height
|| particle.x < 0
|| particle.x > canvas.width
|| particle.alpha <= 0
) {
particles.splice(i, 1);
}
});
requestAnimationFrame(loop);
};
let createFirework = (
x = Math.random() * canvas.width,
y = Math.random() * canvas.height
) => {
let speed = (Math.random() * 2) + BASE_PARTICLE_SPEED;
let maxSpeed = speed;
let red = ~~(Math.random() * 255);
let green = ~~(Math.random() * 255);
let blue = ~~(Math.random() * 255);
// use brighter colours
red = (red < 150 ? red + 150 : red);
green = (green < 150 ? green + 150 : green);
blue = (blue < 150 ? blue + 150 : blue);
// inner firework
for (let i = 0; i < PARTICLES_PER_FIREWORK; i++) {
let particle = new Particle(x, y, red, green, blue, speed);
particles.push(particle);
maxSpeed = (speed > maxSpeed ? speed : maxSpeed);
}
// outer edge particles to make the firework appear more full
for (let i = 0; i < 40; i++) {
let particle = new Particle(x, y, red, green, blue, maxSpeed, true);
particles.push(particle);
}
};
class Particle {
constructor(
x = 0,
y = 0,
red = ~~(Math.random() * 255),
green = ~~(Math.random() * 255),
blue = ~~(Math.random() * 255),
speed,
isFixedSpeed
) {
this.x = x;
this.y = y;
this.red = red;
this.green = green;
this.blue = blue;
this.alpha = 0.05;
this.radius = 1 + Math.random();
this.angle = Math.random() * 360;
this.speed = (Math.random() * speed) + 0.1;
this.velocityX = Math.cos(this.angle) * this.speed;
this.velocityY = Math.sin(this.angle) * this.speed;
this.startTime = (new Date()).getTime();
this.duration = Math.random() * 300 + FIREWORK_LIFESPAN;
this.currentDiration = 0;
this.dampening = 30; // slowing factor at the end
this.colour = this.getColour();
if (isFixedSpeed) {
this.speed = speed;
this.velocityY = Math.sin(this.angle) * this.speed;
this.velocityX = Math.cos(this.angle) * this.speed;
}
this.initialVelocityX = this.velocityX;
this.initialVelocityY = this.velocityY;
}
animate() {
this.currentDuration = (new Date()).getTime() - this.startTime;
// initial speed kick
if (this.currentDuration <= 200) {
this.x += this.initialVelocityX * PARTICLE_INITIAL_SPEED;
this.y += this.initialVelocityY * PARTICLE_INITIAL_SPEED;
this.alpha += 0.01;
this.colour = this.getColour(240, 240, 240, 0.9);
} else {
// normal expansion
this.x += this.velocityX;
this.y += this.velocityY;
this.colour = this.getColour(this.red, this.green, this.blue, 0.4 + (Math.random() * 0.3));
}
this.velocityY += GRAVITY / 1000;
// slow down particles at the end
if (this.currentDuration >= this.duration) {
this.velocityX -= this.velocityX / this.dampening;
this.velocityY -= this.velocityY / this.dampening;
}
if (this.currentDuration >= this.duration + this.duration / 1.1) {
// fade out at the end
this.alpha -= 0.02;
this.colour = this.getColour();
} else {
// fade in during expansion
if (this.alpha < 1) {
this.alpha += 0.03;
}
}
}
render() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true);
ctx.lineWidth = this.lineWidth;
ctx.fillStyle = this.colour;
ctx.shadowBlur = 8;
ctx.shadowColor = this.getColour(this.red + 150, this.green + 150, this.blue + 150, 1);
ctx.fill();
}
getColour(red, green, blue, alpha) {
return `rgba(${red || this.red}, ${green || this.green}, ${blue || this.blue}, ${alpha || this.alpha})`;
}
}
let updateCanvasSize = () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
};
// run it!
updateCanvasSize();
$(window).resize(updateCanvasSize);
$(canvas).on('click', (e) => {
createFirework(e.clientX, e.clientY);
// stop fireworks when clicked, re-enable after short time
disableAutoFireworks = true;
clearTimeout(resetDisable);
resetDisable = setTimeout(() => {
disableAutoFireworks = false;
}, 5000);
});
loop();
//]]>
</script>
3- Hiệu ứng pháo hoa 3Demo trên codepen
DEMO
CÀI ĐẶT
Bước 1:
Bước này thực hiện như bước 1 của hiệu ứng 1
Bước 2:
Thêm javascript sau vào trước </body>
<script type='text/javascript'>
//<![CDATA[
// when animating on canvas, it is best to use requestAnimationFrame instead of setTimeout or setInterval
// not supported in all browsers though and sometimes needs a prefix, so we need a shim
window.requestAnimFrame = ( function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function( callback ) {
window.setTimeout( callback, 1000 / 60 );
};
})();
// now we will setup our basic variables for the demo
var canvas = document.getElementById( 'canvas' ),
ctx = canvas.getContext( '2d' ),
// full screen dimensions
cw = window.innerWidth,
ch = window.innerHeight,
// firework collection
fireworks = [],
// particle collection
particles = [],
// starting hue
hue = 120,
// when launching fireworks with a click, too many get launched at once without a limiter, one launch per 5 loop ticks
limiterTotal = 20,
limiterTick = 0,
// this will time the auto launches of fireworks, one launch per 80 loop ticks
timerTotal = 500,
timerTick = 0,
mousedown = false,
// mouse x coordinate,
mx,
// mouse y coordinate
my;
// set canvas dimensions
canvas.width = cw;
canvas.height = ch;
// now we are going to setup our function placeholders for the entire demo
// get a random number within a range
function random( min, max ) {
return Math.random() * ( max - min ) + min;
}
// calculate the distance between two points
function calculateDistance( p1x, p1y, p2x, p2y ) {
var xDistance = p1x - p2x,
yDistance = p1y - p2y;
return Math.sqrt( Math.pow( xDistance, 2 ) + Math.pow( yDistance, 2 ) );
}
// create firework
function Firework( sx, sy, tx, ty ) {
// actual coordinates
this.x = sx;
this.y = sy;
// starting coordinates
this.sx = sx;
this.sy = sy;
// target coordinates
this.tx = tx;
this.ty = ty;
// distance from starting point to target
this.distanceToTarget = calculateDistance( sx, sy, tx, ty );
this.distanceTraveled = 0;
// track the past coordinates of each firework to create a trail effect, increase the coordinate count to create more prominent trails
this.coordinates = [];
this.coordinateCount = 3;
// populate initial coordinate collection with the current coordinates
while( this.coordinateCount-- ) {
this.coordinates.push( [ this.x, this.y ] );
}
this.angle = Math.atan2( ty - sy, tx - sx );
this.speed = 2;
this.acceleration = 1.05;
this.brightness = random( 50, 70 );
// circle target indicator radius
this.targetRadius = 1;
}
// update firework
Firework.prototype.update = function( index ) {
// remove last item in coordinates array
this.coordinates.pop();
// add current coordinates to the start of the array
this.coordinates.unshift( [ this.x, this.y ] );
// cycle the circle target indicator radius
if( this.targetRadius < 8 ) {
this.targetRadius += 0.3;
} else {
this.targetRadius = 1;
}
// speed up the firework
this.speed *= this.acceleration;
// get the current velocities based on angle and speed
var vx = Math.cos( this.angle ) * this.speed,
vy = Math.sin( this.angle ) * this.speed;
// how far will the firework have traveled with velocities applied?
this.distanceTraveled = calculateDistance( this.sx, this.sy, this.x + vx, this.y + vy );
// if the distance traveled, including velocities, is greater than the initial distance to the target, then the target has been reached
if( this.distanceTraveled >= this.distanceToTarget ) {
createParticles( this.tx, this.ty );
// remove the firework, use the index passed into the update function to determine which to remove
fireworks.splice( index, 1 );
} else {
// target not reached, keep traveling
this.x += vx;
this.y += vy;
}
}
// draw firework
Firework.prototype.draw = function() {
ctx.beginPath();
// move to the last tracked coordinate in the set, then draw a line to the current x and y
ctx.moveTo( this.coordinates[ this.coordinates.length - 1][ 0 ], this.coordinates[ this.coordinates.length - 1][ 1 ] );
ctx.lineTo( this.x, this.y );
ctx.strokeStyle = 'hsl(' + hue + ', 100%, ' + this.brightness + '%)';
ctx.stroke();
ctx.beginPath();
// draw the target for this firework with a pulsing circle
//ctx.arc( this.tx, this.ty, this.targetRadius, 0, Math.PI * 2 );
ctx.stroke();
}
// create particle
function Particle( x, y ) {
this.x = x;
this.y = y;
// track the past coordinates of each particle to create a trail effect, increase the coordinate count to create more prominent trails
this.coordinates = [];
this.coordinateCount = 5;
while( this.coordinateCount-- ) {
this.coordinates.push( [ this.x, this.y ] );
}
// set a random angle in all possible directions, in radians
this.angle = random( 0, Math.PI * 2 );
this.speed = random( 1, 10 );
// friction will slow the particle down
this.friction = 0.95;
// gravity will be applied and pull the particle down
this.gravity = 0.6;
// set the hue to a random number +-20 of the overall hue variable
this.hue = random( hue - 20, hue + 20 );
this.brightness = random( 50, 80 );
this.alpha = 1;
// set how fast the particle fades out
this.decay = random( 0.0075, 0.009 );
}
// update particle
Particle.prototype.update = function( index ) {
// remove last item in coordinates array
this.coordinates.pop();
// add current coordinates to the start of the array
this.coordinates.unshift( [ this.x, this.y ] );
// slow down the particle
this.speed *= this.friction;
// apply velocity
this.x += Math.cos( this.angle ) * this.speed;
this.y += Math.sin( this.angle ) * this.speed + this.gravity;
// fade out the particle
this.alpha -= this.decay;
// remove the particle once the alpha is low enough, based on the passed in index
if( this.alpha <= this.decay ) {
particles.splice( index, 1 );
}
}
// draw particle
Particle.prototype.draw = function() {
ctx. beginPath();
// move to the last tracked coordinates in the set, then draw a line to the current x and y
ctx.moveTo( this.coordinates[ this.coordinates.length - 1 ][ 0 ], this.coordinates[ this.coordinates.length - 1 ][ 1 ] );
ctx.lineTo( this.x, this.y );
ctx.strokeStyle = 'hsla(' + this.hue + ', 100%, ' + this.brightness + '%, ' + this.alpha + ')';
ctx.stroke();
}
// create particle group/explosion
function createParticles( x, y ) {
// increase the particle count for a bigger explosion, beware of the canvas performance hit with the increased particles though
var particleCount = 20;
while( particleCount-- ) {
particles.push( new Particle( x, y ) );
}
}
// main demo loop
function loop() {
// this function will run endlessly with requestAnimationFrame
requestAnimFrame( loop );
// increase the hue to get different colored fireworks over time
hue += 0.5;
// normally, clearRect() would be used to clear the canvas
// we want to create a trailing effect though
// setting the composite operation to destination-out will allow us to clear the canvas at a specific opacity, rather than wiping it entirely
ctx.globalCompositeOperation = 'destination-out';
// decrease the alpha property to create more prominent trails
ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
ctx.fillRect( 0, 0, cw, ch );
// change the composite operation back to our main mode
// lighter creates bright highlight points as the fireworks and particles overlap each other
ctx.globalCompositeOperation = 'lighter';
// loop over each firework, draw it, update it
var i = fireworks.length;
while( i-- ) {
fireworks[ i ].draw();
fireworks[ i ].update( i );
}
// loop over each particle, draw it, update it
var i = particles.length;
while( i-- ) {
particles[ i ].draw();
particles[ i ].update( i );
}
// launch fireworks automatically to random coordinates, when the mouse isn't down
if( timerTick >= timerTotal ) {
timerTick = 0;
} else {
var temp = timerTick % 400;
if(temp <= 15){
fireworks.push( new Firework( 100, ch, random( 190, 200 ), random(90, 100) ));
fireworks.push( new Firework( cw - 100, ch, random(cw - 200, cw - 190), random(90, 100) ));
}
var temp3 = temp / 10;
if(temp > 319){
fireworks.push(new Firework(300 + (temp3 - 31 ) * 100 , ch, 300 + (temp3 - 31) * 100 , 200));
}
timerTick++;
}
// limit the rate at which fireworks get launched when mouse is down
if( limiterTick >= limiterTotal ) {
if( mousedown ) {
// start the firework at the bottom middle of the screen, then set the current mouse coordinates as the target
fireworks.push( new Firework( cw / 2, ch, mx, my ) );
limiterTick = 0;
}
} else {
limiterTick++;
}
}
// mouse event bindings
// update the mouse coordinates on mousemove
canvas.addEventListener( 'mousemove', function( e ) {
mx = e.pageX - canvas.offsetLeft;
my = e.pageY - canvas.offsetTop;
});
// toggle mousedown state and prevent canvas from being selected
canvas.addEventListener( 'mousedown', function( e ) {
e.preventDefault();
mousedown = true;
});
canvas.addEventListener( 'mouseup', function( e ) {
e.preventDefault();
mousedown = false;
});
// once the window loads, we are ready for some fireworks!
window.onload = loop;
//]]>
</script>
4- Hiệu ứng pháo hoa 4Đây là code tạo pháo hoa cho nền body,với hiệu ứng này pháo hoa không ào ạt mà chỉ có tính chất điểm tô cho nền blogspot mà cụ thể chỉ thấy ở các khe trống giữa main và sidebar và toàn bộ body khi xem trên laptop.
Khi rê chuột vào vùng hiệu ứng có hiệu lực, chỏ chuột có hình dấu cộng và pháo hoa sẽ xuất hiện nếu nhấp chuột.
Xem trên codepen
DEMO
Thực hiện:
Bước 1:
Dán đoạn css sau vào trước thẻ </head>
<style type='text/css'>
canvas{
cursor:crosshair;
position:fixed;
width:100%;
height:100%;
background:#222;
display:block
</style>Bước 2:Thêm HTML sau vào ngay sau <body>
<canvas id='canvas' ></canvas>Bước 3:
Dán javascript sau vào trước thẻ </body>
<script type='text/javascript'>
//<![CDATA[
window.requestAnimFrame = ( function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function( callback ) {
window.setTimeout( callback, 1000 / 60 );
};
})();
var canvas = document.getElementById( 'canvas' ),
ctx = canvas.getContext( '2d' ),
cw = window.innerWidth,
ch = window.innerHeight,
fireworks = [],
particles = [],
hue = 120,
limiterTotal = 5,
limiterTick = 0,
timerTotal = 80,
timerTick = 0,
mousedown = false,
mx,
my;
canvas.width = cw;
canvas.height = ch;
function random( min, max ) {
return Math.random() * ( max - min ) + min;
}
function calculateDistance( p1x, p1y, p2x, p2y ) {
var xDistance = p1x - p2x,
yDistance = p1y - p2y;
return Math.sqrt( Math.pow( xDistance, 2 ) + Math.pow( yDistance, 2 ) );
}
function Firework( sx, sy, tx, ty ) {
this.x = sx;
this.y = sy;
this.sx = sx;
this.sy = sy;
this.tx = tx;
this.ty = ty;
this.distanceToTarget = calculateDistance( sx, sy, tx, ty );
this.distanceTraveled = 0;
this.coordinates = [];
this.coordinateCount = 3;
while( this.coordinateCount-- ) {
this.coordinates.push( [ this.x, this.y ] );
}
this.angle = Math.atan2( ty - sy, tx - sx );
this.speed = 2;
this.acceleration = 1.05;
this.brightness = random( 50, 70 );
this.targetRadius = 1;
}
Firework.prototype.update = function( index ) {
this.coordinates.pop();
this.coordinates.unshift( [ this.x, this.y ] );
if( this.targetRadius < 8 ) {
this.targetRadius += 0.3;
} else {
this.targetRadius = 1;
}
this.speed *= this.acceleration;
var vx = Math.cos( this.angle ) * this.speed,
vy = Math.sin( this.angle ) * this.speed;
this.distanceTraveled = calculateDistance( this.sx, this.sy, this.x + vx, this.y + vy );
if( this.distanceTraveled >= this.distanceToTarget ) {
createParticles( this.tx, this.ty );
fireworks.splice( index, 1 );
} else {
this.x += vx;
this.y += vy;
}
}
Firework.prototype.draw = function() {
ctx.beginPath();
ctx.moveTo( this.coordinates[ this.coordinates.length - 1][ 0 ], this.coordinates[ this.coordinates.length - 1][ 1 ] );
ctx.lineTo( this.x, this.y );
ctx.strokeStyle = 'hsl(' + hue + ', 100%, ' + this.brightness + '%)';
ctx.stroke();
ctx.beginPath();
ctx.arc( this.tx, this.ty, this.targetRadius, 0, Math.PI * 2 );
ctx.stroke();
}
function Particle( x, y ) {
this.x = x;
this.y = y;
this.coordinates = [];
this.coordinateCount = 5;
while( this.coordinateCount-- ) {
this.coordinates.push( [ this.x, this.y ] );
}
this.angle = random( 0, Math.PI * 2 );
this.speed = random( 1, 10 );
this.friction = 0.95;
this.gravity = 1;
this.hue = random( hue - 50, hue + 50 );
this.brightness = random( 50, 80 );
this.alpha = 1;
this.decay = random( 0.015, 0.03 );
}
Particle.prototype.update = function( index ) {
this.coordinates.pop();
this.coordinates.unshift( [ this.x, this.y ] );
this.speed *= this.friction;
this.x += Math.cos( this.angle ) * this.speed;
this.y += Math.sin( this.angle ) * this.speed + this.gravity;
this.alpha -= this.decay;
if( this.alpha <= this.decay ) {
particles.splice( index, 1 );
}
}
Particle.prototype.draw = function() {
ctx. beginPath();
ctx.moveTo( this.coordinates[ this.coordinates.length - 1 ][ 0 ], this.coordinates[ this.coordinates.length - 1 ][ 1 ] );
ctx.lineTo( this.x, this.y );
ctx.strokeStyle = 'hsla(' + this.hue + ', 100%, ' + this.brightness + '%, ' + this.alpha + ')';
ctx.stroke();
}
function createParticles( x, y ) {
var particleCount = 30;
while( particleCount-- ) {
particles.push( new Particle( x, y ) );
}
}
function loop() {
requestAnimFrame( loop );
hue= random(0, 360 );
ctx.globalCompositeOperation = 'destination-out';
ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
ctx.fillRect( 0, 0, cw, ch );
ctx.globalCompositeOperation = 'lighter';
var i = fireworks.length;
while( i-- ) {
fireworks[ i ].draw();
fireworks[ i ].update( i );
}
var i = particles.length;
while( i-- ) {
particles[ i ].draw();
particles[ i ].update( i );
}
if( timerTick >= timerTotal ) {
if( !mousedown ) {
fireworks.push( new Firework( cw / 2, ch, random( 0, cw ), random( 0, ch / 2 ) ) );
timerTick = 0;
}
} else {
timerTick++;
}
if( limiterTick >= limiterTotal ) {
if( mousedown ) {
fireworks.push( new Firework( cw / 2, ch, mx, my ) );
limiterTick = 0;
}
} else {
limiterTick++;
}
}
canvas.addEventListener( 'mousemove', function( e ) {
mx = e.pageX - canvas.offsetLeft;
my = e.pageY - canvas.offsetTop;
});
canvas.addEventListener( 'mousedown', function( e ) {
e.preventDefault();
mousedown = true;
});
canvas.addEventListener( 'mouseup', function( e ) {
e.preventDefault();
mousedown = false;
});
window.onload = loop;
//]]>
</script>
Lưu ý:Với trường hợp bạn muốn giữ nguyên màu nền blogspot thì thực hiện như sau:
- Bỏ qua bước 1.
- Bước 2 thay bằng code:
<canvas height='900' id='canvas' style='position:fixed;width:100%;pointer-events:none;z-index:9999;' width='1440'/>- Bước 3 như ở trên.
Mặc định mật độ pháo hoa với trị số 80 nếu bạn muốn pháo hoa ào ạt hơn cho sướng thì giảm trị số này đi:
timerTotal = 80,
5- Hiệu ứng pháo hoa 5
Demo trên codepen
DEMO
CÀI ĐẶT
Bước 1:
Thêm đoạn HTML vào ngay sau <body>
<canvas height='900' id='canvas' style='position:fixed;width:100%;pointer-events:none;z-index:9999;' width='1440'/>Bước 2:
Thêm javascript sau vào trước </body>
<script>/*<![CDATA[*/
(function () {
'use strict';
var canvas = document.querySelector('canvas'),
ctx = canvas.getContext('2d'),
W = canvas.width = window.innerWidth,
H = canvas.height = window.innerHeight,
maxP = 700,
minP = 1000,
fireworks = [];
function tick() {
var newFireworks = [];
ctx.clearRect(0, 0, W, H);
fireworks.forEach(function (firework) {
firework.draw();
if (!firework.done) newFireworks.push(firework);
});
fireworks = newFireworks;
window.requestAnimationFrame(tick);
}
function Vector(x, y) {
this.x = x;
this.y = y;
}
Vector.prototype = {
constructor: Vector,
add: function (vector) {
this.x += vector.x;
this.y += vector.y;
},
diff: function (vector) {
var target = this.copy();
return Math.sqrt(
(target.x-=vector.x) * target.x + (target.y-=vector.y) * target.y
);
},
copy: function () {
return new Vector(this.x, this.y);
}
};
var colors = [
['rgba(179,255,129,', 'rgba(0,255,0,'], //green / white
['rgba(0,0,255,', 'rgba(100,217,255,'], //blue / cyan
['rgba(255,0,0,', 'rgba(255,255,0,'], //red / yellow
['rgba(145,0,213,', 'rgba(251,144,204,'] //purple / pink
];
function Firework(start, target, speed) {
this.start = start;
this.pos = this.start.copy();
this.target = target;
this.spread = Math.round(Math.random() * (maxP-minP)) + minP;
this.distance = target.diff(start);
this.speed = speed || Math.random() * 5 + 15;
this.angle = Math.atan2(target.y - start.y, target.x - start.x);
this.velocity = new Vector(
Math.cos(this.angle) * this.speed,
Math.sin(this.angle) * this.speed
);
this.particals = [];
this.prevPositions = [];
var colorSet = colors[Math.round(Math.random() * (colors.length -1))];
for (var i=0; i<this.spread; i++) {
this.particals.push(new Partical(target.copy(), colorSet));
}
}
Firework.prototype = {
constructor: Firework,
draw: function () {
var last = this.prevPositions[this.prevPositions.length -1] || this.pos;
ctx.beginPath();
ctx.moveTo(last.x, last.y);
ctx.lineTo(this.pos.x, this.pos.y);
ctx.strokeStyle = 'rgba(255,255,255,.7)';
ctx.stroke();
this.update();
},
update: function () {
if (this.start.diff(this.pos) >= this.distance) {
var newParticals = [];
this.particals.forEach(function (partical) {
partical.draw();
if (!partical.done) newParticals.push(partical);
});
this.particals = newParticals;
this.prevPositions = [];
if (!newParticals.length) this.done = true;
} else {
this.prevPositions.push(this.pos.copy());
if (this.prevPositions.length > 8) {
this.prevPositions.shift();
}
this.pos.add(this.velocity);
}
}
};
function Partical(pos, colors) {
this.pos = pos;
this.ease = 0.2;
this.speed = Math.random() * 6 + 2;
this.gravity = Math.random() * 3 + 0.1;
this.alpha = .8;
this.angle = Math.random() * (Math.PI*2);
this.color = colors[Math.round(Math.random() * (colors.length - 1))];
this.prevPositions = [];
}
Partical.prototype = {
constructor: Partical,
draw: function () {
var last = this.prevPositions[this.prevPositions.length -1] || this.pos;
ctx.beginPath();
ctx.moveTo(last.x, last.y);
ctx.lineTo(this.pos.x, this.pos.y);
ctx.strokeStyle = this.color + this.alpha + ')';
ctx.stroke();
this.update();
},
update: function () {
if (this.alpha <= 0) {
this.done = true;
} else {
this.prevPositions.push(this.pos.copy());
if (this.prevPositions.length > 10) this.prevPositions.shift();
if (this.speed > 1) this.speed -= this.ease;
this.alpha -= 0.01;
this.gravity += 0.01;
this.pos.add({
x: Math.cos(this.angle) * this.speed,
y: Math.sin(this.angle) * this.speed + this.gravity
});
}
}
};
function addFirework(target) {
var startPos = new Vector(W/2, H);
target = target || new Vector(Math.random() * W, Math.random() * (H - 300));
fireworks.push(new Firework(startPos, target));
}
canvas.addEventListener('click', function (e) {
addFirework(new Vector(e.clientX, e.clientY))
}, false);
function randomFirework() {
addFirework();
window.setTimeout(randomFirework, Math.random() * 1200);
}
tick();
randomFirework();
})();
/*]]>*/</script>
Tăng giảm mật độ pháo hoa bạn chỉnh sửa trị số 1200, với trị số càng nhỏ mật độ càng lớn.
function randomFirework() {
addFirework();
window.setTimeout(randomFirework, Math.random() * 1200);
}
6- Hiệu ứng pháo hoa 6Demo trên codepen
DEMO
CÀI ĐẶT
Bước 1:
Thêm đoạn HTML vào ngay sau <body>
<canvas height='900' id='fireworks-canvas' style='position:fixed;width:100%;pointer-events:none;z-index:9999;' width='1440'/>Bước 2:
Thêm javascript sau vào trước </body>
<script>/*<![CDATA[*/
window.onload = function () {
var firework = JS_FIREWORKS.Fireworks({
id : 'fireworks-canvas',
hue : 120,
particleCount : 50,
delay : 0,
minDelay : 20,
maxDelay : 20,
boundaries : {
top: 0,
bottom: 150,
left: 40,
right: 1500
},
fireworkSpeed : 1,
fireworkAcceleration : 1.05,
particleFriction : .95,
particleGravity : 1.5
});
firework.start();
};
/**
* @required:
*/
var JS_FIREWORKS = JS_FIREWORKS || {};
JS_FIREWORKS.Fireworks = function (options) {
'use strict';
if (!(this instanceof JS_FIREWORKS.Fireworks)) {
return new JS_FIREWORKS.Fireworks(options);
}
options = options || {};
var _self = this,
_NS = JS_FIREWORKS,
_Class = _NS.Fireworks,
_proto = _Class.prototype,
_canvas = document.getElementById(options.id || 'fireworks-canvas'),
_ctx = _canvas.getContext ? _canvas.getContext('2d') : null,
_width = _canvas.width,
_height = _canvas.height,
_hue = options.hue || 120,
_isRunning = false,
_fireworks = [],
_particles = [],
_particleCount = options.particleCount || 50,
_tick = 0,
_delay = options.delay || 30,
_minDelay = options.minDelay || 30,
_maxDelay = options.maxDelay || 90,
_boundaries = options.boundaries || {
top : 50,
bottom : _height * .5,
left : 50,
right : _width - 50
},
_loop = _NS.getRenderLoop(),
_randRange = _NS.randomRange,
_randIntRange = _NS.randomIntRange,
_Firework = _NS.Firework,
_Particle = _NS.Particle;
_Class.settings = {
fireworkSpeed : options.fireworkSpeed || 2,
fireworkAcceleration : options.fireworkAcceleration || 1.05,
particleFriction : options.particleFriction || .95,
particleGravity : options.particleGravity || 1.5
};
_Class.version = '1.0.2';
_self.start = function () {
_isRunning = true;
_fireworks = [];
_particles = [];
_render();
};
_self.stop = function () {
_isRunning = false;
_self.clear();
};
_self.isRunning = function () {
return _isRunning;
};
_self.clear = function () {
if (!_ctx) {
return;
}
_ctx.globalCompositeOperation = 'source-over';
_ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
_ctx.fillRect(0, 0, _width, _height);
};
var _render = function () {
if (!_ctx || !_isRunning) {
return;
}
var tmp, count;
_loop(_render);
_hue += 0.5;
_ctx.globalCompositeOperation = 'destination-out';
_ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
_ctx.fillRect(0, 0, _width, _height);
_ctx.globalCompositeOperation = 'lighter';
tmp = _fireworks.length;
// render fireworks
while (tmp--) {
_fireworks[tmp].draw();
_fireworks[tmp].update( function (x, y, hue) {
count = _particleCount;
while (count--) {
_particles.push(_Particle(x, y, _ctx, hue));
}
_fireworks.splice(tmp, 1);
});
}
// render particles
tmp = _particles.length;
while (tmp--) {
_particles[tmp].draw();
_particles[tmp].update( function () {
_particles.splice(tmp, 1);
});
}
// spawn firework
if (_tick === _delay) {
_fireworks.push(_Firework(
_width * .5,
_height,
_randIntRange(_boundaries.left, _boundaries.right),
_randIntRange(_boundaries.top, _boundaries.bottom),
_ctx,
_hue
));
_delay = _randIntRange(_minDelay, _maxDelay);
_tick = 0;
}
_tick++;
};
return _self;
};
JS_FIREWORKS.Firework = function (x1, y1, x2, y2, context, hue) {
'use strict';
if (!(this instanceof JS_FIREWORKS.Firework)) {
return new JS_FIREWORKS.Firework(x1, y1, x2, y2, context, hue);
}
var _self = this,
_NS = JS_FIREWORKS,
_Class = _NS.Firework,
_proto = _Class.prototype,
_settings = JS_FIREWORKS.Fireworks.settings,
_x = x1,
_y = y1,
_sx = x1,
_sy = y1,
_dx = x2,
_dy = y2,
_ctx = context,
_totalDistance = 0,
_currentDistance = 0,
_coordinates = [],
_coordinateCount = 3,
_angle = 0,
_speed = _settings.fireworkSpeed,
_acceleration = _settings.fireworkAcceleration,
_hue = hue,
_brightness = 0,
_randIntRange = _NS.randomIntRange,
_distance = _NS.distance,
_sin = Math.sin,
_cos = Math.cos;
_self.update = function (callback) {
_coordinates.pop();
_coordinates.unshift([_x, _y]);
_speed *= _acceleration;
var vx = _cos(_angle) * _speed,
vy = _sin(_angle) * _speed;
_currentDistance = _distance(_sx, _sy, _x + vx, _y + vy);
if (_currentDistance >= _totalDistance) {
callback(_dx, _dy, _hue);
} else {
_x += vx;
_y += vy;
}
};
_self.draw = function () {
var last = _coordinates.length - 1;
_ctx.beginPath();
_ctx.moveTo(_coordinates[last][0], _coordinates[last][1]);
_ctx.lineTo(_x, _y);
_ctx.strokeStyle = 'hsl(' + _hue + ', 100%, ' + _brightness + '%)';
_ctx.stroke();
};
( function () {
_totalDistance = _distance(_sx, _sy, _dx, _dy);
while (_coordinateCount--) {
_coordinates.push([_x, _y]);
}
_angle = Math.atan2(_dy - _sy, _dx - _sx);
_brightness = _randIntRange(50, 70);
})();
return _self;
};
JS_FIREWORKS.Particle = function (x, y, context, hue) {
'use strict';
if (!(this instanceof JS_FIREWORKS.Particle)) {
return new JS_FIREWORKS.Particle(x, y, context, hue);
}
var _self = this,
_NS = JS_FIREWORKS,
_Class = _NS.Particle,
_proto = _Class.prototype,
_settings = JS_FIREWORKS.Fireworks.settings,
_x = x,
_y = y,
_ctx = context,
_coordinates = [],
_coordinateCount = 5,
_angle = 0,
_speed = 0,
_friction = _settings.particleFriction,
_gravity = _settings.particleGravity,
_hue = hue,
_brightness = 0,
_alpha = 1,
_decay = 0,
_randRange = _NS.randomRange,
_randIntRange = _NS.randomIntRange,
_2PI = Math.PI * 2,
_sin = Math.sin,
_cos = Math.cos;
_self.update = function (callback) {
_coordinates.pop();
_coordinates.unshift([_x, _y]);
_speed *= _friction;
_x += _cos(_angle) * _speed;
_y += _sin(_angle) * _speed + _gravity;
_alpha -= _decay;
if (_alpha <= _decay) {
callback();
}
};
_self.draw = function () {
var last = _coordinates.length - 1;
_ctx.beginPath();
_ctx.moveTo(_coordinates[last][0], _coordinates[last][1]);
_ctx.lineTo(_x, _y);
_ctx.strokeStyle = 'hsla(' + _hue + ', 100%, ' + _brightness + '%, ' + _alpha + ')';
_ctx.stroke();
};
( function () {
while (_coordinateCount--) {
_coordinates.push([_x, _y ]);
}
_angle = _randRange(0, _2PI);
_speed = _randIntRange(1, 10);
_hue = _randIntRange(_hue - 20, _hue + 20);
_brightness = _randIntRange(50, 80);
_decay = _randRange(.015, .03);
})();
return _self;
};
JS_FIREWORKS.randomRange = function (min, max) {
return (Math.random() * ( max - min ) + min);
};
JS_FIREWORKS.randomIntRange = function (min, max) {
return JS_FIREWORKS.randomRange(min, max)|0;
};
JS_FIREWORKS.distance = function (x1, y1, x2, y2) {
var pow = Math.pow;
return Math.sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2));
};
JS_FIREWORKS.getRenderLoop = function () {
return (
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (callback) {
return window.setTimeout(callback, 1000 / 60);
}
);
};
/*]]>*/</script>
Xem thêm một số cách trang trí khác cho Blogspot
- Code dây đèn nhấp nháy và hiệu ứng pháo hoa cho blog nền đen- Hiệu ứng pháo hoa cho blogspot nền đen
- Tạo pháo hoa năm mới
- Trang trí tết Kỷ Hợi 2019
- Tuyết rơi và chữ Merry chrismas
- Ông già Nô En cưỡi tuần lộc
- Tạo đồng hồ đếm ngược với javascript
- Code tạo chuông Giáng Sinh
- Trang trí tết cho blogspot
