通过canvas画出爱心图案,表达你的爱意!
创始人
2024-05-29 22:31:05
0

在这里插入图片描述
通过canvas画出爱心图案,浏览器可以使用以下js代码,新建对象时,会自动呈现动画效果,代码文末可下载。

点击免费下载源码

let HeartCanvas = new HeartCanvas()

/*** 爱心* Heart Canvas*/class HeartCanvas {/*** @param hMin 颜色 h 最小值* @param hMax 颜色 h 最大值* @param countHeart 心的数量* @param sizeMin 心形最小值* @param sizeMax 心形最大值* @param bgColor 背景颜色*/constructor(hMin, hMax, countHeart = 150, sizeMin = 50, sizeMax = 350, bgColor) {this.isPlaying = true // 默认自动播放this.mouseX = 0this.mouseY = 0this.configFrame = {width : 1200,height: 300,bgColor: bgColor}this.configHeart = {timeLine: 0,                           // 时间线timeInit: new Date().getTime(),movement: 1,                           // 运动速度x: 50,                                 // 位置 xy: 50,                                 // 位置 ywidth: 200,                            // heart 大小height: 200,                           // heart 大小countHeart: countHeart || 150,         // heart 数量// 大小sizeMin: isNaN(sizeMin) ?50: sizeMin,  // 最小值sizeMax: isNaN(sizeMax) ?350: sizeMax, // 最大值// 颜色colorSaturate: 100,                    // 颜色饱和度 0-100colorLight: 60,                        // 颜色亮度 0-100hMin: isNaN(hMin) ?330: hMin,          // 色值最小hMax: isNaN(hMax) ?350: hMax,          // 色值最大minOpacity: 20,                        // 透明度最小 %maxOpacity: 100,                       // 透明度最大 %opacityGrowth: 5,                      // 透明度增长值// 出现的位置范围heartRangeMin: 0,                      // 心出现的位置,从下面算起,取值 0.0-1.0heartRangeMax: 0.3,// 加速度gravityMin: 1,                         // 加速度 mingravityMax: 9.8,                       // 加速度 maxflowDirection: 1,                      // 运动方向 1 向上 -1 向下}this.heartBuffer = [] // 心缓存this.init()window.onresize = () => {this.configFrame.height = innerHeight * 2this.configFrame.width = innerWidth * 2let heartLayer = document.getElementById('heartLayer')this.updateFrameAttribute(heartLayer)}}play(){if (this.isPlaying){} else {this.isPlaying = truethis.draw()}}stop(){this.isPlaying = false}moveDown(){this.configHeart.flowDirection = -1}moveUp(){this.configHeart.flowDirection = 1}speedUp(){}speedDown(){}destroy(){this.isPlaying = falselet heartLayer = document.getElementById('heartLayer')heartLayer.remove()console.log('动画已停止')}updateFrameAttribute(heartLayer){heartLayer.setAttribute('id', 'heartLayer')heartLayer.setAttribute('width', this.configFrame.width)heartLayer.setAttribute('height', this.configFrame.height)heartLayer.style.width = `${this.configFrame.width / 2}px`heartLayer.style.height = `${this.configFrame.height / 2}px`heartLayer.style.zIndex = '-3'heartLayer.style.userSelect = 'none'heartLayer.style.position = 'fixed'heartLayer.style.top = '0'heartLayer.style.left = '0'}init(){this.configFrame.height = innerHeight * 2this.configFrame.width = innerWidth * 2let heartLayer = document.createElement("canvas")this.updateFrameAttribute(heartLayer)document.documentElement.append(heartLayer)this.configHeart.timeLine =  0// 填充缓存形状for (let i = 0; i < this.configHeart.countHeart; i++) {let randomSize = randomInt(this.configHeart.sizeMin, this.configHeart.sizeMax)let x = randomInt(0, this.configFrame.width)let y = randomInt(this.configFrame.height * (1-this.configHeart.heartRangeMax), this.configFrame.height * (1-this.configHeart.heartRangeMin))this.heartBuffer.push({id: i,gravity: randomFloat(this.configHeart.gravityMin, this.configHeart.gravityMax),opacity: 0,opacityFinal: randomInt(this.configHeart.minOpacity, this.configHeart.maxOpacity), // 最终透明度timeInit: randomInt(1, 500), // 随机排布初始 heart 的位置x, // 位置 xy, // 位置 yoriginalX: x,originalY: y,width: randomSize,  // heart 大小height: randomSize, // heart 大小colorH: randomInt(this.configHeart.hMin, this.configHeart.hMax)})}this.draw()document.documentElement.addEventListener('mousemove', event => {this.mouseX = event.xthis.mouseY = event.y})}// 判断鼠标跟 box 的距离isMouseIsCloseToBox(box){let distance = Math.sqrt(Math.pow(Math.abs(box.position.x / 2 - this.mouseX),2) + Math.pow(Math.abs(box.position.y /2  - this.mouseY), 2))return distance < 100}draw() {// 建立自己的时间参考线,消除使用系统时间时导致的切换程序后时间紊乱的情况this.configHeart.timeLine = this.configHeart.timeLine + 1// create heartlet canvasHeart = document.getElementById('heartLayer')let contextHeart = canvasHeart.getContext('2d')contextHeart.clearRect(0, 0, this.configFrame.width, this.configFrame.height)// 背景,没有 bgColor 的时候,背景就是透明的if (this.configFrame.bgColor){contextHeart.fillStyle = this.configFrame.bgColorcontextHeart.fillRect(0,0,this.configFrame.width, this.configFrame.height)}this.heartBuffer.forEach(heart => {// 当出了画面时if (heart.y < -(heart.height)){heart.y = heart.originalYheart.timeInit = this.configHeart.timeLine // 重新定位时间节点heart.opacity = 0}// 当透明度到达最终透明度时let timeGap = this.configHeart.timeLine - heart.timeInit // 时间为正数时才计算透明度if (timeGap > 0){heart.opacity = heart.opacity * ((this.configHeart.timeLine - heart.timeInit)/100)} else { // 没到该 heart 的展示时间时,透明度为 0,不显示heart.opacity = 0}if (heart.opacity >= heart.opacityFinal){heart.opacity = heart.opacityFinal // 定位到最终的透明度}// 1/2 gt㎡  运动轨迹// let movement = 1/2 * this.configHeart.gravity * Math.pow((new Date().getTime() - heart.timeInit)/1000,2)// speed = 1/2 gtlet movement = 1/2 * heart.gravity * (this.configHeart.timeLine - heart.timeInit) / 300 * this.configHeart.flowDirectionheart.y = heart.y - movementthis.drawHeart(heart.x,heart.y,heart.width / 2,heart.height / 2,`hsl(${heart.colorH} ${this.configHeart.colorSaturate}% ${this.configHeart.colorLight}% / ${heart.opacity}%)`)heart.opacity = heart.opacity + this.configHeart.opacityGrowth})if (this.isPlaying) {window.requestAnimationFrame(() => {this.draw()})}}// 画一个心drawHeart(x, y, width, height, colorFill) {let canvasHeart = document.getElementById('heartLayer')let contextHeart = canvasHeart.getContext('2d')contextHeart.save()contextHeart.beginPath()let topCurveHeight = height * 0.3contextHeart.moveTo(x, y + topCurveHeight)// top left curvecontextHeart.bezierCurveTo(x, y,x - width / 2, y,x - width / 2, y + topCurveHeight)// bottom left curvecontextHeart.bezierCurveTo(x - width / 2, y + (height + topCurveHeight) / 2,x, y + (height + topCurveHeight) / 1.4,x, y + height)// bottom right curvecontextHeart.bezierCurveTo(x, y + (height + topCurveHeight) / 1.8,x + width / 2, y + (height + topCurveHeight) / 2,x + width / 2, y + topCurveHeight)// top right curvecontextHeart.bezierCurveTo(x + width / 2, y,x, y,x, y + topCurveHeight)contextHeart.closePath()contextHeart.fillStyle = colorFillcontextHeart.fill()contextHeart.restore()}}/*** 输出随机 1 或 -1* @returns {number}*/
function randomDirection(){let random = Math.random()if (random > 0.5){return 1} else {return -1}
}/*** 生成随机整数* @param min* @param max* @returns {number}*/
function randomInt(min, max){return Number((Math.random() * (max - min) + min).toFixed(0))
}/*** 生成随机整数* @param min* @param max* @returns {number}*/
function randomFloat(min, max){return Number(Math.random() * (max - min) + min)
}

Vue可通过以下方式导入,代码在文末可下载:

import {HeartCanvas} from "animate-heart-canvas"export default {mounted() {this.height = innerHeightthis.animateHeartCanvas = new AnimateHeartCanvas()},beforeDestroy() {this.animateHeartCanvas.destroy()}
}

API

  • @param hMin 颜色 h 最小值
  • @param hMax 颜色 h 最大值
  • @param countHeart 心的数量
  • @param sizeMin 心形最小值
  • @param sizeMax 心形最大值
  • @param bgColor 背景颜色

let HeartCanvas = new HeartCanvas(hMin, hMax, countHeart, sizeMin, sizeMax, bgColor)
// hMin hMax 对应 hue 的颜色值
// 什么参数都不写就是红色

let 五颜六色 = new HeartCanvas(0, 360) // 这个就是五颜六色的

// 其它操作
HeartCanvas.play() // 心动起来
HeartCanvas.stop() // 心不动
HeartCanvas.moveUp() // 心向上走
HeartCanvas.moveDown() // 心向下走

点击免费下载源码

相关内容

热门资讯

122.(leaflet篇)l... 听老人家说:多看美女会长寿 地图之家总目录(订阅之前建议先查看该博客) 文章末尾处提供保证可运行...
育碧GDC2018程序化大世界... 1.传统手动绘制森林的问题 采用手动绘制的方法的话,每次迭代地形都要手动再绘制森林。这...
育碧GDC2018程序化大世界... 1.传统手动绘制森林的问题 采用手动绘制的方法的话,每次迭代地形都要手动再绘制森林。这...
Vue使用pdf-lib为文件... 之前也写过两篇预览pdf的,但是没有加水印,这是链接:Vu...
PyQt5数据库开发1 4.1... 文章目录 前言 步骤/方法 1 使用windows身份登录 2 启用混合登录模式 3 允许远程连接服...
Android studio ... 解决 Android studio 出现“The emulator process for AVD ...
Linux基础命令大全(上) ♥️作者:小刘在C站 ♥️个人主页:小刘主页 ♥️每天分享云计算网络运维...
再谈解决“因为文件包含病毒或潜... 前面出了一篇博文专门来解决“因为文件包含病毒或潜在的垃圾软件”的问题,其中第二种方法有...
南京邮电大学通达学院2023c... 题目展示 一.问题描述 实验题目1 定义一个学生类,其中包括如下内容: (1)私有数据成员 ①年龄 ...
PageObject 六大原则 PageObject六大原则: 1.封装服务的方法 2.不要暴露页面的细节 3.通过r...
【Linux网络编程】01:S... Socket多进程 OVERVIEWSocket多进程1.Server2.Client3.bug&...
数据结构刷题(二十五):122... 1.122. 买卖股票的最佳时机 II思路:贪心。把利润分解为每天为单位的维度,然后收...
浏览器事件循环 事件循环 浏览器的进程模型 何为进程? 程序运行需要有它自己专属的内存空间࿰...
8个免费图片/照片压缩工具帮您... 继续查看一些最好的图像压缩工具,以提升用户体验和存储空间以及网站使用支持。 无数图像压...
计算机二级Python备考(2... 目录  一、选择题 1.在Python语言中: 2.知识点 二、基本操作题 1. j...
端电压 相电压 线电压 记得刚接触矢量控制的时候,拿到板子,就赶紧去测各种波形,结...
如何使用Python检测和识别... 车牌检测与识别技术用途广泛,可以用于道路系统、无票停车场、车辆门禁等。这项技术结合了计...
带环链表详解 目录 一、什么是环形链表 二、判断是否为环形链表 2.1 具体题目 2.2 具体思路 2.3 思路的...
【C语言进阶:刨根究底字符串函... 本节重点内容: 深入理解strcpy函数的使用学会strcpy函数的模拟实现⚡strc...
Django web开发(一)... 文章目录前端开发1.快速开发网站2.标签2.1 编码2.2 title2.3 标题2.4 div和s...