New Year’s Eve is coming soon, let’s use JS to set fireworks on your web page


First look at the effect

https://www.bilibili.com/video/bv1fr4y1T7TB

Insert picture description here

Insert picture description here

The Spring Festival is about to be celebrated. In big cities, it is still not allowed to set off fireworks and other air-polluting things. I miss the happy time of putting flowers in my yard when I was young. Children in big cities can't realize this kind of happiness. . But as a front-end engineer, this is not difficult for us. Here is how to use JS to set fireworks on the web.

Search for "fireworks" in codepen , you can find all kinds of fireworks effects done using JS. The code I shared today is also a reference from one of them. After reading this article, it is guaranteed that you can write the effects of fireworks on any platform and in any language.
Insert picture description here

How to achieve it?

Create a Canvas first


First create a new canvas with the same size as the visible area of ​​the webpage, and change the size of the canvas by monitoring the resize event of the display area.

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');

function resizeCanvas() {
    
    
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
}

function clearCanvas(){
    
    
	context.fillStyle = '#ffffff';
	context.fillRect(0,0,canvas.width, canvas.height);
}

window.addEventListener('resize', resizeCanvas, false);
resizeCanvas();

Practice before setting off fireworks


Fireworks explode from one point and spread out with different arcs, so we first draw a few small dots around a circle center. A bit like a small circle of loading. This is actually the initial state of the fireworks...

function mouseDownHandler(e) {
    
    
    var x = e.clientX;
    var y = e.clientY;

    drawFireworks(x,y);
}

function drawFireworks(sx,sy) {
    
    
    var count = 10;//烟花粒子数量
    var radius = 10;//烟花环绕半径

    for(var i = 0 ;i<count;i++){
    
    
        var angle = 360/count*i;//烟花粒子角度
        var radians = angle * Math.PI / 180;//烟花粒子弧度

        var vx = sx+Math.cos(radians) * radius;
        var vy = sy+Math.sin(radians) * radius;

        var size = 2;
        context.beginPath();
        context.arc(vx, vy, size, 0, Math.PI*2, false)
        context.closePath();
        context.fillStyle = "#ff0000";
        context.fill();
    }
}

document.addEventListener('mousedown', mouseDownHandler, false);

Everyone should understand the meaning of the above code, right? But now there is no animation, nothing like fireworks. Don't worry, we will make them move right away.

Move


To move is actually to continuously draw a center radius whose value increases from small to large... You can understand that there are two methods for constant drawing, setInterval and requestAnimationFrame, both methods are available.

1.setInterval

Advantage: It is easier to set the drawing frequency of animation.

var radius = 0;//圆心半径
function fire(x,y){
    
    
    function tick() {
    
    
        drawFireworks(x,y);//绘制烟花
        radius++;//半径不断变大
    }
    setInterval(tick,30);//每30毫秒绘制一次
}

2.requestAnimationFrame

Advantages: The drawing frequency is synchronized with the drawing of the browser screen.

var radius = 0;
function fire(x,y){
    
    
    function tick() {
    
    
        drawFireworks(x,y);
        radius++;
        requestAnimationFrame(tick);
    }
    tick();
}

Do you feel a little bit already?

More like fireworks


But real fireworks will definitely not be so obedient, keeping the arc and speed in a regular manner, so we need to add some random factors.

var rid;
function fire(x,y){
    
    
    createFireworks(x,y);

    function tick() {
    
    
        drawFireworks();
        rid=requestAnimationFrame(tick);
    }
    cancelAnimationFrame(rid);
    tick();
}

var particles=[];
function createFireworks(sx,sy){
    
    
    particles=[];

    var hue = Math.floor(Math.random()*51)+150;
    var hueVariance = 30;
    var count = 100;

    for(var i = 0 ;i<count;i++){
    
    
        var p = {
    
    };

        var angle = Math.floor(Math.random()*360);
        p.radians = angle * Math.PI / 180;
        p.radius = 0;

        p.sx = sx;
        p.sy = sy;

        p.speed = (Math.random()*5)+.4;

        p.size = Math.floor(Math.random()*3)+1;

        p.hue = Math.floor(Math.random()*((hue+hueVariance)-(hue-hueVariance)))+(hue-hueVariance);
        p.brightness = Math.floor(Math.random()*31)+50;
        p.alpha = (Math.floor(Math.random()*61)+40)/100;

        particles.push(p);
    }
}

function drawFireworks() {
    
    
    clearCanvas();

    for(var i = 0 ;i<particles.length;i++){
    
    
        var p = particles[i];

        p.vx = p.sx+Math.cos(p.radians) * p.radius;
        p.vy = p.sy+Math.sin(p.radians) * p.radius;

        p.radius += 1+p.speed;

        context.beginPath();
        context.arc(p.vx, p.vy, p.size, 0, Math.PI*2, false);
        context.closePath();

        context.fillStyle = 'hsla('+p.hue+', 100%, '+p.brightness+'%, '+100+')';
        context.fill();
    }
}

Then we add a little smoke trailing effect to it

function tick() {
    
    
	//tips:注意新加入的这4行代码
	context.globalCompositeOperation = 'destination-out';
	context.fillStyle = 'rgba(0,0,0,'+10/100+')';
	context.fillRect(0,0,canvas.width,canvas.height);
	context.globalCompositeOperation = 'lighter';
	//tipsend
	drawFireworks();
	rid=requestAnimationFrame(tick);
}

In order to be more realistic, some gravity effects are now added to make the movement speed of the firework particles slower and slower and gradually disappear.

var vx = Math.cos(p.radians) * p.radius;
var vy = Math.sin(p.radians) * p.radius + 0.4;

p.x += vx;
p.y += vy;

p.radius *= 1 - p.speed/100;

p.alpha -= 0.005;

Now this firework looks like a firework. Of course, you can add some more detailed variables to various parameters. For example, draw a firecracker and launch it into the sky from the firecracker. The last is the fireworks... Let everyone do it.

Set fireworks on any webpage


Create a bookmark in Chrome, copy the following code, paste it into the URL field, and save.

https://www.bilibili.com/video/bv1fr4y1T7TB

Insert picture description here

javascript: !(function() {
    
    
	var cdom = document.createElement("canvas");
	cdom.id = "myCanvas";
	cdom.style.position = "fixed";
	cdom.style.left = "0";
	cdom.style.top = "0";
	cdom.style.zIndex = -1;
	document.body.appendChild(cdom);
	var canvas = document.getElementById('myCanvas');
	var context = canvas.getContext('2d');

	function resizeCanvas() {
    
    
		canvas.width = window.innerWidth;
		canvas.height = window.innerHeight;
	}
	window.addEventListener('resize', resizeCanvas, false);
	resizeCanvas();
	clearCanvas();

	function clearCanvas() {
    
    
		context.fillStyle = '#000000';
		context.fillRect(0, 0, canvas.width, canvas.height);
	}

	function mouseDownHandler(e) {
    
    
		var x = e.clientX;
		var y = e.clientY;
		fire(x, y);
	}
	var rid;

	function fire(x, y) {
    
    
		createFireworks(x, y);

		function tick() {
    
    
			context.globalCompositeOperation = 'destination-out';
			context.fillStyle = 'rgba(0,0,0,' + 10 / 100 + ')';
			context.fillRect(0, 0, canvas.width, canvas.height);
			context.globalCompositeOperation = 'lighter';
			drawFireworks();
			rid = requestAnimationFrame(tick);
		}
		cancelAnimationFrame(rid);
		tick();
	}
	var particles = [];

	function createFireworks(sx, sy) {
    
    
		particles = [];
		var hue = Math.floor(Math.random() * 51) + 150;
		var hueVariance = 30;
		var count = 100;
		for (var i = 0; i < count; i++) {
    
    
			var p = {
    
    };
			var angle = Math.floor(Math.random() * 360);
			p.radians = angle * Math.PI / 180;
			p.x = sx;
			p.y = sy;
			p.speed = (Math.random() * 5) + .4;
			p.radius = p.speed;
			p.size = Math.floor(Math.random() * 3) + 1;
			p.hue = Math.floor(Math.random() * ((hue + hueVariance) - (hue - hueVariance))) + (hue - hueVariance);
			p.brightness = Math.floor(Math.random() * 31) + 50;
			p.alpha = (Math.floor(Math.random() * 61) + 40) / 100;
			particles.push(p);
		}
	}

	function drawFireworks() {
    
    
		clearCanvas();
		for (var i = 0; i < particles.length; i++) {
    
    
			var p = particles[i];
			var vx = Math.cos(p.radians) * p.radius;
			var vy = Math.sin(p.radians) * p.radius + 0.4;
			p.x += vx;
			p.y += vy;
			p.radius *= 1 - p.speed / 100;
			p.alpha -= 0.005;
			context.beginPath();
			context.arc(p.x, p.y, p.size, 0, Math.PI * 2, false);
			context.closePath();
			context.fillStyle = 'hsla(' + p.hue + ', 100%, ' + p.brightness + '%, ' + p.alpha + ')';
			context.fill();
		}
	}
	document.addEventListener('mousedown', mouseDownHandler, false);
})();

Source download

https://download.csdn.net/download/qq_44273429/14218941

Guess you like

Origin blog.csdn.net/qq_44273429/article/details/112624783