爱心代码

简述:
这段代码利用Canvas和JavaScript实现了一个简单的粒子效果,通过绘制爱心形状的粒子并随机生成、更新、绘制粒子,最终形成一个动态的爱心粒子效果。以下是代码的简要分析:

  1. 代码通过设置HTML和CSS来创建网页的基本结构和样式。

  2. JavaScript部分的代码主要负责定义了一些类和函数,以及实现了粒子效果的渲染逻辑。

  3. settings对象包含了粒子效果的一些设置参数,如粒子数量、持续时间、速度、大小等。

  4. Point类表示一个点的坐标,具有计算点的长度、归一化等方法。

  5. Particle类表示一个粒子对象,具有位置、速度、加速度和年龄等属性,以及初始化、更新和绘制等方法。

  6. ParticlePool类表示粒子池,用于管理粒子对象的创建、更新和绘制等操作。

  7. 匿名函数通过使用Canvas绘制爱心的路径和填充颜色来创建粒子的图像。

  8. render函数是主要的渲染函数,通过不断更新时间、清空画布、创建新粒子和更新、绘制粒子等步骤实现粒子效果的动画效果。

  9. onResize函数用于处理画布大小的调整。

  10. 最后,通过获取页面中的Canvas元素,并将其作为参数传递给匿名函数,启动了粒子效果的渲染。

生成方式:文本加‘.html’后缀

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>canvas爱心</title><style>
html, body {height: 100%;padding: 0;margin: 0;background: #000;
}
canvas {position: absolute;width: 100%;height: 100%;
}</style>
</head>
<body><canvas id="pinkboard"></canvas><script>
/** Settings*/
var settings = {particles: {length:   500, // maximum amount of particlesduration:   2, // particle duration in secvelocity: 100, // particle velocity in pixels/seceffect: -0.75, // play with this for a nice effectsize:      30, // particle size in pixels},
};/** RequestAnimationFrame polyfill by Erik M?ller*/
(function(){var b=0;var c=["ms","moz","webkit","o"];for(var a=0;a<c.length&&!window.requestAnimationFrame;++a){window.requestAnimationFrame=window[c[a]+"RequestAnimationFrame"];window.cancelAnimationFrame=window[c[a]+"CancelAnimationFrame"]||window[c[a]+"CancelRequestAnimationFrame"]}if(!window.requestAnimationFrame){window.requestAnimationFrame=function(h,e){var d=new Date().getTime();var f=Math.max(0,16-(d-b));var g=window.setTimeout(function(){h(d+f)},f);b=d+f;return g}}if(!window.cancelAnimationFrame){window.cancelAnimationFrame=function(d){clearTimeout(d)}}}());/** Point class*/
var Point = (function() {function Point(x, y) {this.x = (typeof x !== 'undefined') ? x : 0;this.y = (typeof y !== 'undefined') ? y : 0;}Point.prototype.clone = function() {return new Point(this.x, this.y);};Point.prototype.length = function(length) {if (typeof length == 'undefined')return Math.sqrt(this.x * this.x + this.y * this.y);this.normalize();this.x *= length;this.y *= length;return this;};Point.prototype.normalize = function() {var length = this.length();this.x /= length;this.y /= length;return this;};return Point;
})();/** Particle class*/var Particle = (function() {function Particle() {this.position = new Point();this.velocity = new Point();this.acceleration = new Point();this.age = 0;}Particle.prototype.initialize = function(x, y, dx, dy) {this.position.x = x;this.position.y = y;this.velocity.x = dx;this.velocity.y = dy;this.acceleration.x = dx * settings.particles.effect;this.acceleration.y = dy * settings.particles.effect;this.age = 0;};Particle.prototype.update = function(deltaTime) {this.position.x += this.velocity.x * deltaTime;this.position.y += this.velocity.y * deltaTime;this.velocity.x += this.acceleration.x * deltaTime;this.velocity.y += this.acceleration.y * deltaTime;this.age += deltaTime;};Particle.prototype.draw = function(context, image) {function ease(t) {return (--t) * t * t + 1;}var size = image.width * ease(this.age / settings.particles.duration);context.globalAlpha = 1 - this.age / settings.particles.duration;context.drawImage(image, this.position.x - size / 2, this.position.y - size / 2, size, size);};return Particle;
})();/** ParticlePool class*/
var ParticlePool = (function() {var particles,firstActive = 0,firstFree   = 0,duration    = settings.particles.duration;function ParticlePool(length) {// create and populate particle poolparticles = new Array(length);for (var i = 0; i < particles.length; i++)particles[i] = new Particle();}ParticlePool.prototype.add = function(x, y, dx, dy) {particles[firstFree].initialize(x, y, dx, dy);// handle circular queuefirstFree++;if (firstFree   == particles.length) firstFree   = 0;if (firstActive == firstFree       ) firstActive++;if (firstActive == particles.length) firstActive = 0;};ParticlePool.prototype.update = function(deltaTime) {var i;// update active particlesif (firstActive < firstFree) {for (i = firstActive; i < firstFree; i++)particles[i].update(deltaTime);}if (firstFree < firstActive) {for (i = firstActive; i < particles.length; i++)particles[i].update(deltaTime);for (i = 0; i < firstFree; i++)particles[i].update(deltaTime);}// remove inactive particleswhile (particles[firstActive].age >= duration && firstActive != firstFree) {firstActive++;if (firstActive == particles.length) firstActive = 0;}};ParticlePool.prototype.draw = function(context, image) {// draw active particlesif (firstActive < firstFree) {for (i = firstActive; i < firstFree; i++)particles[i].draw(context, image);}if (firstFree < firstActive) {for (i = firstActive; i < particles.length; i++)particles[i].draw(context, image);for (i = 0; i < firstFree; i++)particles[i].draw(context, image);}};return ParticlePool;
})();/** Putting it all together*/
(function(canvas) {var context = canvas.getContext('2d'),particles = new ParticlePool(settings.particles.length),particleRate = settings.particles.length / settings.particles.duration, // particles/sectime;// get point on heart with -PI <= t <= PIfunction pointOnHeart(t) {return new Point(160 * Math.pow(Math.sin(t), 3),130 * Math.cos(t) - 50 * Math.cos(2 * t) - 20 * Math.cos(3 * t) - 10 * Math.cos(4 * t) + 25);}// creating the particle image using a dummy canvasvar image = (function() {var canvas  = document.createElement('canvas'),context = canvas.getContext('2d');canvas.width  = settings.particles.size;canvas.height = settings.particles.size;// helper function to create the pathfunction to(t) {var point = pointOnHeart(t);point.x = settings.particles.size / 2 + point.x * settings.particles.size / 350;point.y = settings.particles.size / 2 - point.y * settings.particles.size / 350;return point;}// create the pathcontext.beginPath();var t = -Math.PI;var point = to(t);context.moveTo(point.x, point.y);while (t < Math.PI) {t += 0.01; // baby steps!point = to(t);context.lineTo(point.x, point.y);}context.closePath();// create the fillcontext.fillStyle = '#ea80b0';context.fill();// create the imagevar image = new Image();image.src = canvas.toDataURL();return image;})();// render that thing!function render() {// next animation framerequestAnimationFrame(render);// update timevar newTime   = new Date().getTime() / 1000,deltaTime = newTime - (time || newTime);time = newTime;// clear canvascontext.clearRect(0, 0, canvas.width, canvas.height);// create new particlesvar amount = particleRate * deltaTime;for (var i = 0; i < amount; i++) {var pos = pointOnHeart(Math.PI - 2 * Math.PI * Math.random());var dir = pos.clone().length(settings.particles.velocity);particles.add(canvas.width / 2 + pos.x, canvas.height / 2 - pos.y, dir.x, -dir.y);}// update and draw particlesparticles.update(deltaTime);particles.draw(context, image);}// handle (re-)sizing of the canvasfunction onResize() {canvas.width  = canvas.clientWidth;canvas.height = canvas.clientHeight;}window.onresize = onResize;// delay rendering bootstrapsetTimeout(function() {onResize();render();}, 10);
})(document.getElementById('pinkboard'));</script></body>
</html>

Canvas和JavaScript实现动态爱心粒子效果相关推荐

  1. JavaScript绘制动画爱心

    东西内容比较多,不细述写,但很多代码里面都有对应注释供学习参考 ​ <!DOCTYPE html> <html> <head><meta http-equiv ...

  2. 微信小程序 | canvas为你的天气预报添加雨雪效果

    在 Canvas 开发中,经常会提到粒子系统,使用粒子系统可以模拟出火.雾.云.雪等抽象视觉效果.它是HTML5新增的为页面添加多样化效果的绝佳实践. 正巧最近做的一个天气类微信小程序紧接尾声,寻思着 ...

  3. canvas为你的天气预报添加雨雪效果 | 微信小程序

    关注 前端瓶子君,回复"交流" 加入我们一起学习,天天进步 来源:行舟客 https://yunxiaomeng.blog.csdn.net/article/details/110 ...

  4. Canvas实现HTML动态粒子效果背景

    之前参考诸多博客,发现许多博主自定义的博客主页都会有很多动态的小粒子在页面漂浮,鼠标经过还会有响应事件,在这里,将代码记录一下. 首先,在html页面要先定义一个canvas元素: <canva ...

  5. html5 图片粒子效果,Canvas + JavaScript 制作图片粒子效果

    首先看一下源图和转换成粒子效果的对比图: 左侧图片为源图,右侧图片为粒子效果图.该效果是在Canvas画布上制作的.将图片制作成粒子效果相对而言是比较简单的.重点了解两个知识点即可 1:图片是通过im ...

  6. 用Python制作一个动态爱心效果!

    大家好,我是小F- 最近「点燃我,温暖你」这部剧非常火,讲述的是程序员的爱情故事. 其中陈飞宇饰演的男主李峋,在剧中用程序做出的爱心跳动效果,非常炫. 网上各个大佬也是纷纷给出看法,综合就是不太可能用 ...

  7. 「点燃我,温暖你」用Python制作一个动态爱心效果

    最近「点燃我,温暖你」这部剧非常火,讲述的是程序员的爱情故事. 其中陈飞宇饰演的男主李峋,在剧中用程序做出的爱心跳动效果,非常炫. 网上各个大佬也是纷纷给出看法,综合就是不太可能用C语言来实现的. 大 ...

  8. php漂浮雪花,canvas实现雪花随机动态飘落效果(代码示例)

    本篇文章给大家介绍一下使用canvas实现雪花随机动态飘落效果的方法,文中示例代码介绍的非常详细.有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助. 用canvas实现雪花随机动态飘落, ...

  9. 雪花漂浮php,canvas实现雪花随机动态飘落效果(代码示例)

    本篇文章给大家介绍一下使用canvas实现雪花随机动态飘落效果的方法,文中示例代码介绍的非常详细.有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助. 用canvas实现雪花随机动态飘落, ...

最新文章

  1. 想象中的论文答辩和真实的论文答辩,哈哈哈哈哈哈……
  2. Android 唯一标识获取
  3. ubuntu系统虚拟机linux系统,基于虚拟机的Linux操作系统安装(Ubuntu
  4. lua cURL使用笔记
  5. 冒泡和快速排序的时间复杂度_八大排序算法性能分析及总结
  6. C#:解决WCF中服务引用 自动生成代码不全的问题。
  7. 在河北大学就读是怎样一种体验?
  8. springboot 全局捕获异常
  9. Gitlab+Jenkins学习之路(四)之gitlab备份和恢复
  10. 2012年最新75款免费的专业英文字体下载【下篇】
  11. 【语音采集】基于matlab语音采集及处理【含Matlab源码 1737期】
  12. Delphi中TStringList类常用属性方法详解
  13. OSChina 周二乱弹 —— 技术宅正确装逼姿势
  14. Python编程学习:中兴LTE网管MML命令脚本生成器
  15. 软件人员kpi制定模板_软件科技公司绩效考核办法模板.doc
  16. diskpart命令_Windows Diskpart命令教程
  17. 测试必备的15个docker命令,你都掌握了吗
  18. 正则表达式限定输入数字
  19. Unity射线与UI碰撞检测
  20. 【IoT】硬件PM系列(三):硬件产品经理需要掌握的定价策略

热门文章

  1. 【qq机器人】音乐分享
  2. 测试新人如何编写测试用例
  3. httpie实用指南
  4. GoF23-迪米特法则
  5. 【mongodb双响曲】:mongodb的基本使用
  6. Kali系统如何开放ssh端口22
  7. PMP新大纲,3A通过了考试,一点点心得供新人参考
  8. Failed to list units: No such method ‘ListUnitsFiltered‘ systemctl list-units
  9. sqrt函数原型c语言,C语言sqrt函数的实例用法讲解
  10. wsus修改端口80重置服务器节点,windows2008R2上的wsus运行规则报错,要求"重置服务器节点"...