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

本文主要是介绍新年快乐代码-Canvas全屏烟花动画特效_附完整源码【可直接运行】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

  • 🔅新年快乐
    • 🎨效果展示
  • 🍻源码解析
    • 🍕完整源码
  • 🍮寄语

🔅新年快乐

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

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

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

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

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

🎨效果展示

在这里插入图片描述

🍻源码解析

// 解码核心代码
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 dimensionscw = window.innerWidth,ch = window.innerHeight,// firework collectionfireworks = [],// particle collectionparticles = [],// starting huehue = 120,// when launching fireworks with a click, too many get launched at once without a limiter, one launch per 5 loop tickslimiterTotal = 5,limiterTick = 0,// this will time the auto launches of fireworks, one launch per 80 loop tickstimerTotal = 80,timerTick = 0,mousedown = false,// mouse x coordinate,mx,// mouse y coordinatemy;// 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 coordinatesthis.x = sx;this.y = sy;// starting coordinatesthis.sx = sx;this.sy = sy;// target coordinatesthis.tx = tx;this.ty = ty;// distance from starting point to targetthis.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 trailsthis.coordinates = [];this.coordinateCount = 3;// populate initial coordinate collection with the current coordinateswhile( 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 radiusthis.targetRadius = 1;
}// update firework
Firework.prototype.update = function( index ) {// remove last item in coordinates arraythis.coordinates.pop();// add current coordinates to the start of the arraythis.coordinates.unshift( [ this.x, this.y ] );// cycle the circle target indicator radiusif( this.targetRadius < 8 ) {this.targetRadius += 0.3;} else {this.targetRadius = 1;}// speed up the fireworkthis.speed *= this.acceleration;// get the current velocities based on angle and speedvar 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 reachedif( this.distanceTraveled >= this.distanceToTarget ) {createParticles( this.tx, this.ty );// remove the firework, use the index passed into the update function to determine which to removefireworks.splice( index, 1 );} else {// target not reached, keep travelingthis.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 yctx.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 circlectx.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 trailsthis.coordinates = [];this.coordinateCount = 5;while( this.coordinateCount-- ) {this.coordinates.push( [ this.x, this.y ] );}// set a random angle in all possible directions, in radiansthis.angle = random( 0, Math.PI * 2 );this.speed = random( 1, 10 );// friction will slow the particle downthis.friction = 0.95;// gravity will be applied and pull the particle downthis.gravity = 1;// set the hue to a random number +-20 of the overall hue variablethis.hue = random( hue - 20, hue + 20 );this.brightness = random( 50, 80 );this.alpha = 1;// set how fast the particle fades outthis.decay = random( 0.015, 0.03 );
}// update particle
Particle.prototype.update = function( index ) {// remove last item in coordinates arraythis.coordinates.pop();// add current coordinates to the start of the arraythis.coordinates.unshift( [ this.x, this.y ] );// slow down the particlethis.speed *= this.friction;// apply velocitythis.x += Math.cos( this.angle ) * this.speed;this.y += Math.sin( this.angle ) * this.speed + this.gravity;// fade out the particlethis.alpha -= this.decay;// remove the particle once the alpha is low enough, based on the passed in indexif( 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 yctx.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 thoughvar particleCount = 30;while( particleCount-- ) {particles.push( new Particle( x, y ) );}
}// main demo loop
function loop() {// this function will run endlessly with requestAnimationFramerequestAnimFrame( loop );// increase the hue to get different colored fireworks over timehue += 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 entirelyctx.globalCompositeOperation = 'destination-out';// decrease the alpha property to create more prominent trailsctx.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 otherctx.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 itvar i = fireworks.length;while( i-- ) {fireworks[ i ].draw();fireworks[ i ].update( i );}// loop over each particle, draw it, update itvar i = particles.length;while( i-- ) {particles[ i ].draw();particles[ i ].update( i );}// launch fireworks automatically to random coordinates, when the mouse isn't downif( 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 screenfor(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 downif( limiterTick >= limiterTotal ) {if( mousedown ) {// start the firework at the bottom middle of the screen, then set the current mouse coordinates as the targetfireworks.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>

🍮寄语

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

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

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

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

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

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

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

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

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

这篇关于新年快乐代码-Canvas全屏烟花动画特效_附完整源码【可直接运行】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/753833

相关文章

Java NoClassDefFoundError运行时错误分析解决

《JavaNoClassDefFoundError运行时错误分析解决》在Java开发中,NoClassDefFoundError是一种常见的运行时错误,它通常表明Java虚拟机在尝试加载一个类时未能... 目录前言一、问题分析二、报错原因三、解决思路检查类路径配置检查依赖库检查类文件调试类加载器问题四、常见

SpringBoot整合OpenFeign的完整指南

《SpringBoot整合OpenFeign的完整指南》OpenFeign是由Netflix开发的一个声明式Web服务客户端,它使得编写HTTP客户端变得更加简单,本文为大家介绍了SpringBoot... 目录什么是OpenFeign环境准备创建 Spring Boot 项目添加依赖启用 OpenFeig

利用Python调试串口的示例代码

《利用Python调试串口的示例代码》在嵌入式开发、物联网设备调试过程中,串口通信是最基础的调试手段本文将带你用Python+ttkbootstrap打造一款高颜值、多功能的串口调试助手,需要的可以了... 目录概述:为什么需要专业的串口调试工具项目架构设计1.1 技术栈选型1.2 关键类说明1.3 线程模

Python Transformers库(NLP处理库)案例代码讲解

《PythonTransformers库(NLP处理库)案例代码讲解》本文介绍transformers库的全面讲解,包含基础知识、高级用法、案例代码及学习路径,内容经过组织,适合不同阶段的学习者,对... 目录一、基础知识1. Transformers 库简介2. 安装与环境配置3. 快速上手示例二、核心模

Python如何精准判断某个进程是否在运行

《Python如何精准判断某个进程是否在运行》这篇文章主要为大家详细介绍了Python如何精准判断某个进程是否在运行,本文为大家整理了3种方法并进行了对比,有需要的小伙伴可以跟随小编一起学习一下... 目录一、为什么需要判断进程是否存在二、方法1:用psutil库(推荐)三、方法2:用os.system调用

Java的栈与队列实现代码解析

《Java的栈与队列实现代码解析》栈是常见的线性数据结构,栈的特点是以先进后出的形式,后进先出,先进后出,分为栈底和栈顶,栈应用于内存的分配,表达式求值,存储临时的数据和方法的调用等,本文给大家介绍J... 目录栈的概念(Stack)栈的实现代码队列(Queue)模拟实现队列(双链表实现)循环队列(循环数组

SpringBoot多数据源配置完整指南

《SpringBoot多数据源配置完整指南》在复杂的企业应用中,经常需要连接多个数据库,SpringBoot提供了灵活的多数据源配置方式,以下是详细的实现方案,需要的朋友可以参考下... 目录一、基础多数据源配置1. 添加依赖2. 配置多个数据源3. 配置数据源Bean二、JPA多数据源配置1. 配置主数据

SpringBoot中配置Redis连接池的完整指南

《SpringBoot中配置Redis连接池的完整指南》这篇文章主要为大家详细介绍了SpringBoot中配置Redis连接池的完整指南,文中的示例代码讲解详细,具有一定的借鉴价值,感兴趣的小伙伴可以... 目录一、添加依赖二、配置 Redis 连接池三、测试 Redis 操作四、完整示例代码(一)pom.

Java 正则表达式URL 匹配与源码全解析

《Java正则表达式URL匹配与源码全解析》在Web应用开发中,我们经常需要对URL进行格式验证,今天我们结合Java的Pattern和Matcher类,深入理解正则表达式在实际应用中... 目录1.正则表达式分解:2. 添加域名匹配 (2)3. 添加路径和查询参数匹配 (3) 4. 最终优化版本5.设计思

使用Java将DOCX文档解析为Markdown文档的代码实现

《使用Java将DOCX文档解析为Markdown文档的代码实现》在现代文档处理中,Markdown(MD)因其简洁的语法和良好的可读性,逐渐成为开发者、技术写作者和内容创作者的首选格式,然而,许多文... 目录引言1. 工具和库介绍2. 安装依赖库3. 使用Apache POI解析DOCX文档4. 将解析