canvas烟花-娱乐
网上看到一个释放烟花的canvas案例,很好看哦。
新建文本,把下面代码复制进去,后缀名改为html,用浏览器打开即可。
看懂注释后,可以自己修改烟花的各个效果。我试过让烟花炸成了心型。:-)
<!DOCTYPE html>
<html dir="ltr" lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<title>HTML5 Canvas烟花特效 场景十分华丽在线演示</title>
<style>
/* basic styles for black background and crosshair cursor */
body {
background: #;
margin: ;
} canvas {
cursor: crosshair;
display: block;
}
</style> </head>
<body>
<div style="text-align:center;clear:both">
<script src="/gg_bd_ad_720x90.js" type="text/javascript"></script>
<script src="/follow.js" type="text/javascript"></script>
</div>
<canvas id="canvas">Canvas is not supported in your browser.</canvas>
<script>
// 当动画在canvas上,最好使用requestAnimationFrame代替setTimeout和setInterval
// 不支持在所有的浏览器,有时需要一个前缀,所以我们需要一个重置
window.requestAnimFrame = (function () {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function (callback) {
window.setTimeout(callback, / );
};
})(); // 设置基本变量
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
// 全屏幕尺寸
cw = window.innerWidth,
ch = window.innerHeight,
// firework collection 烟花集合
fireworks = [],
// particle collection 爆炸粒子集合
particles = [],
// starting hue 开始色调
hue = ,
// when launching fireworks with a click, too many get launched at once without a limiter, one launch per 5 loop ticks
// 通过点击释放烟花没有限制,每5次循环释放一次
limiterTotal = ,
limiterTick = ,
// this will time the auto launches of fireworks, one launch per 80 loop ticks
// 自动发射80循环一次
timerTotal = ,
timerTick = ,
mousedown = false,
// mouse x coordinate X坐标
mx,
// mouse y coordinate Y坐标
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, ) + Math.pow(yDistance, ));
} // 创建烟花
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 = ;
// 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 = ;
// 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); // 从x轴到指定坐标点(x, y)的角度(以弧度为单位)
this.speed = ; // 速度
this.acceleration = 1.05; // 加速度
this.brightness = random(, ); // 亮度
// circle target indicator radius
// 圆形目标指示器半径
this.targetRadius = ;
} // 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]); // 循环圆形目标指示器半径
if (this.targetRadius < ) {
this.targetRadius += 0.3;
} else {
this.targetRadius = ;
} // speed up the firework 烟花速度
this.speed *= this.acceleration; // get the current velocities based on angle and speed
// 获取x,y两个方向的速度
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, );
} 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
// 移动到最后一个跟踪坐标,然后画一条线到当前的x和y
ctx.moveTo(this.coordinates[this.coordinates.length - ][], this.coordinates[this.coordinates.length - ][]);
ctx.lineTo(this.x, this.y);
// 色调(0或360表示红色,120表示绿色,240表示蓝色);饱和度;亮度
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, , Math.PI * ); // 画圆
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 = ;
while (this.coordinateCount--) {
this.coordinates.push([this.x, this.y]);
}
// set a random angle in all possible directions, in radians
// 在所有可能的方向,设置一个随机角弧度
this.angle = random(, Math.PI * );
this.speed = random(, );
// friction will slow the particle down 摩擦会使粒子慢下来
this.friction = 0.95;
// gravity will be applied and pull the particle down 重力将应用粒子拉下来
this.gravity = ;
// set the hue to a random number +-20 of the overall hue variable
// 在烟花色度范围内随机取爆炸粒子色度
this.hue = random(hue - , hue + );
this.brightness = random(, );
this.alpha = ;
// 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, );
}
} // 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
// 移动到最后一个坐标跟踪设置,然后画一条线到当前的x和y
ctx.moveTo(this.coordinates[this.coordinates.length - ][], this.coordinates[this.coordinates.length - ][]);
ctx.lineTo(this.x, this.y);
// 色调(0或360表示红色,120表示绿色,240表示蓝色);饱和度;亮度
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
// 增加粒子数创造更大的爆炸,谨防增加粒子造成canvas与性能影响
var particleCount = parseInt(random(, ));
while (particleCount--) {
particles.push(new Particle(x, y));
}
} // 主循环
function loop() {
// this function will run endlessly with requestAnimationFrame
// 这个函数将无限运行requestAnimationFrame
requestAnimFrame(loop); // increase the hue to get different colored fireworks over time
// 增加颜度,随着时间的推移得到不同颜色的烟火
hue += random(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
// 设置复合操作destination-out将使我们能够把画布清理在在一个特定的不透明度,而不是完全抹去它
ctx.globalCompositeOperation = 'destination-out'; // 在源图像外显示目标图像。只有源图像外的目标图像部分会被显示,源图像是透明的。
// decrease the alpha property to create more prominent trails
// 降低alpha属性来创建更加显著的轨迹(0.5是透明度)
ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
ctx.fillRect(, , 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);
} // 循环绘制粒子
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) {
var sw = random(, cw);
// 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
// 启动烟花在屏幕中间的底部, 然后设置随机目标坐标, 随机y坐标将范围内的屏幕的上半部分
fireworks.push(new Firework(sw, ch, sw, random(, ch / )));
timerTick = ;
}
} 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(mx, ch, mx, my));
limiterTick = ;
}
} 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
// 切换mousedown状态,防止canvas被选中
canvas.addEventListener('mousedown', function (e) {
e.preventDefault();
mousedown = true;
}); canvas.addEventListener('mouseup', function (e) {
e.preventDefault();
mousedown = false;
}); // 登录启动
window.onload = loop;
</script>
</body>
</html>
canvas烟花-娱乐的更多相关文章
- canvas烟花锦集
canvas可以实现不同动画效果,本文主要记录几种不同节日烟花效果实现. 实现一 效果地址 html <canvas id="canvas"></canvas&g ...
- WEB烟花效果——Canvas实现
摘要 本文主要介绍一种WEB形式的烟花(fireworks)效果(图1所示),该效果基于Canvas实现,巧妙地运用了canvas绘图的特性,并加入了物理力作用的模拟,使整体效果非常绚丽 ...
- HTML5 Canvas 超炫酷烟花绽放动画教程
这是一个很酷的HTML5 Canvas动画,它将模拟的是我们现实生活中烟花绽放的动画特效,效果非常逼真,但是毕竟是电脑模拟,带女朋友看就算了,效果还是差了点,呵呵.这个HTML5 Canvas动画有一 ...
- HTML5 Canvas 超逼真烟花绽放动画
各位前端朋友们,大家好!五一假期即将结束,在开启加班模式之前,我要给大家分享一个超酷超逼真的HTML5 Canvas烟花模拟动画.这次升级版的烟花动画有以下几个特点: 烟花绽放时,将展现不同的色彩,不 ...
- 精选19款华丽的HTML5动画和实用案例
下面是本人收集的19款超酷HTML5动画和实用案例,觉得不错,分享给大家. 1.HTML5 Canvas火焰喷射动画效果 还记得以前分享过的一款HTML5烟花动画HTML5 Canvas烟花特效,今天 ...
- 精妙无比 8款HTML5动画实例及源码
1.jQuery垂直带小图标菜单导航插件 今天我们要来分享一款jQuery菜单插件,这款jQuery菜单是垂直的样式,鼠标滑过菜单项时会出现一个背景,菜单项的右侧也会出现一个小箭头.另外值得注意的是, ...
- HTML5/jQuery动画应用 3D视觉效果
今天我们要来分享几款很酷的HTML5/CSS3动画应用,虽然不是HTML5 3D应用,但也有3D的视觉效果.HTML5结合jQuery,让网页应用变得更加强大了.一起来看看这些HTML5/jQuery ...
- 10款很酷的HTML5动画和实用应用 有源码
10款很酷的HTML5动画和实用应用,这里有菜单.SVG动画.Loading动画,总有你喜欢的,而且,每一款HTML5应用都提供源代码下载,方便大家学习和研究,一起来看看吧. 1.HTML5 SVG ...
- 8个超震撼的HTML5和纯CSS3动画源码
HTML5和CSS3之所以强大,不仅因为现在大量的浏览器的支持,更是因为它们已经越来越能满足现代开发的需要.Flash在几年之后肯定会消亡,那么HTML5和CSS3将会替代Flash.今天我们要给大家 ...
随机推荐
- C#的匿名委托 和 Java的匿名局部内部类
.NET:C#的匿名委托 和 Java的匿名局部内部类 目录 背景实验备注 背景返回目录 这几天重温Java,发现Java在嵌套类型这里提供的特性比较多,结合自身对C#中匿名委托的理解,我大胆的做了一 ...
- 自定义radio图标
问题: 默认的radio控件不是很好看,我们能否自定义一个radio图标? 解决: 1.radio有input和lable两个标签. 2.<input>是前面的图标,选中后图标变化. 3. ...
- EasyUI Editable Tree
效果如图: Create Tree <ul id="tt"></ul> $('#tt').etree({ url: 'tree_data.json', cr ...
- WCF引用方式
WCF之各种WCF引用方式 写在开头:本文内容来自 WCF全面解析中的一个经典例子,如果你已经看过了,那么可以忽略本文,本文旨在和大家分享不一样的WCF使用方法. 准备工作: 1.创建解决方案WCFS ...
- C# 与 C++强强联合--C#中的指针
C# 与 C++强强联合--C#中的指针 非常的不好意思,距离上次随笔C# 与 C++强强联合已经过去快1个月了.承诺大家的C#指针和A*算法迟迟未上.为表歉意献上美女一枚 哈哈.流口水了吧 话归正题 ...
- Python之路3Day
3.python基础补充(集合,collection系列,深浅拷贝) 一.集合 1.集合(set): 把不同的元素组成一起形成集合,是python基本的数据类型.集合元素(set elements ...
- 从零开始学C++之继承(二):继承与构造函数、派生类到基类的转换
一.不能自动继承的成员函数 构造函数 析构函数 =运算符 二.继承与构造函数 基类的构造函数不被继承,派生类中需要声明自己的构造函数. 声明构造函数时,只需要对本类中新增成员进行初始化,对继承来的基类 ...
- 在android里用ExpandableListView实现二层和三层列表
转载自http://www.cnblogs.com/nuliniaoboke/archive/2012/11/13/2767957.html 二层列表是直接用androidAPI中的Expandabl ...
- EF框架操作postgresql,实现WKT类型坐标的插入,查询,以及判断是否相交
1.组件配置 首先,要下载.NET for Postgresql的驱动,npgsql,EF6,以及EntityFramework6.Npgsql,版本号 3.1.1.0. 由于是mvc项目,所以,把相 ...
- SQL如何获取时间的方法?
getdate():当前系统日期与时间 DATEADD(DAY,5,GETDATE()):当前日期的基础上加上x天 DATEDIFF(DAY,'2017-01-02','2017-01-13'):返回 ...