新年快乐代码-Canvas全屏烟花动画特效_附完整源码【可直接运行】

2024-01-02 15:51:11

🔅新年快乐

随着冬日的暖阳洒满大地,新年的钟声在每个人的心中轻轻响起。这是一个充满希望与期待的时刻,一个告别过去、迎接未来的转折点。在这个温馨而又神圣的时刻,我怀揣着满心的祝福,想要对你说一声:新年快乐!

新年的快乐,源自于我们对生活的热爱。无论是忙碌的都市街头,还是宁静的乡村田野,每一个角落都弥漫着浓浓的年味。红灯笼高高挂起,喜庆的对联贴满门窗,孩子们欢声笑语,大人们笑逐颜开。这是一个属于我们的节日,一个让我们放下疲惫、释放欢乐的时刻。

新年的快乐,源自于我们对亲情的珍视。家,永远是最温暖的港湾。无论我们身在何方,心中都有一个永恒的牵挂。在新年的钟声中,让我们向远方的亲人送去最深的思念,向身边的亲人表达最真挚的感激。愿家人们身体健康,幸福安康,愿每一个温馨的家庭都充满欢声笑语。

新年的快乐,源自于我们对友情的珍视。人生路上,有朋友的陪伴,旅途不再孤单。无论是一起分享欢笑泪水的学生时代,还是携手共度风雨的职场生涯,友情如同一盏明灯,照亮我们前行的道路。在新的一年里,愿我们的友情更加深厚,愿我们的友谊天长地久。

在这个充满希望与憧憬的新年之际,让我们携手同行,用笑容点亮生活的色彩,用热情点燃未来的火花。让每一天都成为一段美好的旅程,让每一步都留下坚实的脚印。新年快乐!愿你我的梦想都能成真,愿我们的未来更加美好!

🎨效果展示

在这里插入图片描述

🍻源码解析

// 解码核心代码
var result = "SGFwcHkgTmV3IFllYXI=";

var decodeTxt = window.atob(result);
decodeTxt = decodeURI(decodeTxt);
decodeTxt = decodeTxt.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');

// 在Canvas上绘制解码后的文本
ctx.font = "50px sans-serif";
var textData = ctx.measureText(decodeTxt);
ctx.fillStyle = "rgba(" + parseInt(random(0, 255)) + "," + parseInt(random(0, 255)) + "," + parseInt(random(0, 255)) + ",0.3)";
ctx.fillText(decodeTxt, cw / 2 - textData.width / 2, ch / 2);

for (var h = 0; h < 50; h++) {
    fireworks.push(new Firework(cw / 2, ch / 2, random(0, cw), random(0, ch)));
}

这段源码是一个HTML5 Canvas动画效果,实现了一个全屏烟花的特效。以下是对源码的简要解析:

  1. HTML 结构:

    • 使用HTML5的文档类型声明 <!doctype html>
    • 包含一个 <head> 部分,其中设置了字符集(UTF-8)和页面标题。
    • 包含一个 <body> 部分,其中有一个 <canvas> 元素用于绘制动画。
  2. CSS 样式:

    • 设置了基本的样式,将页面背景设置为黑色,去除了页面的默认边距,将鼠标指针设置为十字叉。
  3. JavaScript 代码:

    • 引入了requestAnimFrame函数,用于优化Canvas动画的更新,兼容不同浏览器。
    • 初始化了Canvas上下文、窗口宽高、烟花和粒子的集合等变量。
    • 定义了一系列函数,用于生成随机数、计算两点间的距离、创建烟花、更新烟花状态、绘制烟花、创建粒子、更新粒子状态、绘制粒子等。
    • 实现了一个主循环 loop(),通过 requestAnimFrame 实现持续更新和绘制动画。
    • 通过鼠标事件监听,获取鼠标位置,并在鼠标点击时触发烟花的发射。
    • 自动触发烟花的发射,通过定时器控制。
  4. Canvas 绘制:

    • 使用Canvas绘制烟花的轨迹和粒子的轨迹,通过改变颜色、透明度等属性实现动画效果。
    • 在Canvas中添加了一段文字,并随着动画的进行,以一定透明度和随机颜色绘制在屏幕中央。

总体而言,这段代码通过Canvas绘图和JavaScript动画实现了一个烟花特效,包括烟花的发射、爆炸效果和粒子的运动轨迹。

🍕完整源码

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>HTML5 Canvas全屏烟花动画特效</title>

<style>
/* basic styles for black background and crosshair cursor */
body {
	background: #000;
	margin: 0;
}

canvas {
	cursor: crosshair;
	display: block;
}
</style>

</head>
<body>

<canvas id="canvas"></canvas>

<script>
// 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 = 5,
		limiterTick = 0,
		// this will time the auto launches of fireworks, one launch per 80 loop ticks
		timerTotal = 80,
		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 = 1;
	// 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.015, 0.03 );
}

// 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 = 30;
	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';
	
	var result = "SGFwcHkgTmV3IFllYXI=";

	var decodeTxt = window.atob(result);
	decodeTxt = decodeURI(decodeTxt);
  ctx.font = "50px sans-serif";
  var textData = ctx.measureText(decodeTxt);
  ctx.fillStyle = "rgba("+parseInt(random(0,255))+","+parseInt(random(0,255))+","+parseInt(random(0,255))+",0.3)";
  ctx.fillText(decodeTxt,cw /2-textData.width/2,ch/2); 
  
	// 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 ) {
		if( !mousedown ) {
			// start the firework at the bottom middle of the screen, then set the random target coordinates, the random y coordinates will be set within the range of the top half of the screen
      
      for(var h=0;h<50;h++)
      {
           fireworks.push( new Firework( cw / 2, ch/2, random( 0, cw ), random( 0, ch  ) ) );
      }
      
      
			timerTick = 0;
		}
	} 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/2, 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>

</body>
</html>

🍮寄语

祝愿你新年快乐,充满喜悦和希望!愿新的一年带给你幸福和成功,让每一个美好的时刻都留下深刻的回忆。愿你在未来的日子里,心想事成,梦想成真。新年到来,愿你收获满满,笑意常驻,一切都如你所愿!

新年伊始,愿你迎接充满阳光、温馨和希望的日子。在这美好的季节里,让我们携手迈入一个全新的征程,充满着梦想和机遇。

新年是一张全新的画布,让我们一同挥洒着五彩斑斓的色彩。愿你的每一天都像绽放的花朵一样美好,每一刻都弥漫着幸福的芬芳。愿你在新的一年里实现更多的梦想,勇敢迎接生活的挑战,书写属于自己的精彩篇章。

时光荏苒,岁月如梭,但在新的一年里,我们有机会重新定义自己,修复过去的遗憾,追逐新的目标。愿你在追梦的路上,拥有坚韧不拔的勇气,克服困难,勇往直前。每一步都是向着成功的方向迈进,每一次努力都是为了更美好的未来。

在新的一年里,愿你心怀感激,珍惜身边的每一个温暖瞬间。生活中的点滴幸福,都是一种无法言喻的财富。与家人朋友共度欢乐时光,分享彼此的快乐和困扰。在困难面前,有爱的支持和温暖,就是最坚强的后盾。

新年带给我们的不仅仅是时光的更替,更是对过去的反思和对未来的展望。愿你在新的一年里不仅保持对自己的自信,更能够放下曾经的包袱,迎接全新的可能。过去的错误不过是人生路上的一次教训,新的一年是弥补和成长的机会。

让我们怀揣着梦想,努力奋斗,迎接新的挑战。在未来的日子里,愿你发现更多的机会,创造更多的价值,成为更好的自己。不管前方有多少坎坷,有多少困难,都请坚信,你拥有足够的勇气和智慧去战胜一切。

新年是希望的季节,是憧憬的时刻。愿你拥有一颗敢于梦想的心,勇往直前,让梦想的翅膀在新的一年里飞得更高。不管岁月如何更迭,我们都能携手共渡风雨,共同创造属于我们的辉煌。

在这个充满祝福和温馨的季节,愿你和家人共同享受温暖的时光。新年的钟声已经敲响,愿幸福和平安如期而至,带给你满满的幸福和快乐。让我们携手迎接新的一年,一起谱写属于我们的新篇章。

文章来源:https://blog.csdn.net/weixin_52908342/article/details/135339256
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。