通过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() // 心向下走

点击免费下载源码

相关内容

热门资讯

安卓系统有avattarify... 你有没有想过,你的安卓手机里有没有一个神奇的魔法师,能帮你把照片变成卡通形象呢?没错,我要说的就是那...
华为系统转安卓手机,迈向自主生... 你有没有想过,你的华为手机里装的那个酷炫的鸿蒙系统,突然有一天你想换回安卓系统,那感觉就像是从一个神...
xp系统导航如何改为安卓系统,... 亲爱的电脑小宝贝,你是不是也厌倦了那个古老的XP系统,想要给它来个时尚的变身,变成一个酷炫的安卓小达...
安卓如何输入系统代码,Andr... 你有没有想过,你的安卓手机里竟然隐藏着这么多的秘密?没错,就是那些神秘的系统代码!今天,就让我带你一...
平板电脑安卓5.2系统,平板电... 你有没有想过,平板电脑的世界里,安卓5.2系统就像是一位低调的舞者,虽然不像安卓最新版那样耀眼,但它...
安卓系统自带录像器,轻松录制精... 亲爱的手机控们,你是否曾有过这样的时刻:想要记录下手机屏幕上的精彩瞬间,却发现没有合适的工具?别担心...
安卓系统下载多多视频,多多视频... 亲爱的手机控们,是不是每天都在为找不到好视频而烦恼呢?别急,今天我要给大家安利一款神器——安卓系统下...
安卓机如何查看系统,安卓系统查... 亲爱的安卓机用户们,你是否曾好奇过自己的手机里藏着哪些秘密?想知道你的安卓机到底是个啥模样?别急,今...
安卓14系统怎么分屏,安卓14... 你有没有发现,现在的手机屏幕越来越大,是不是感觉以前那些单任务的日子已经一去不复返了呢?别急,今天就...
安卓系统平板推荐小孩,助力孩子... 最近是不是也被平板电脑的诱惑给勾住了?尤其是想给家里的宝贝选一款既能学习又能娱乐的安卓系统平板,真是...
最好手机安卓系统,最佳安卓手机... 你有没有想过,为什么你的手机里装的是安卓系统呢?是不是因为它比其他系统更酷、更自由、更符合你的个性?...
安卓系统主题库在哪,主题生成的... 你有没有想过,让你的安卓手机也来个华丽变身,变成一个酷炫的苹果小精灵呢?别急,今天我就要给你揭秘安卓...
双系统平板升级安卓,双系统平板... 亲爱的平板用户们,你们有没有发现,最近平板界的风头可是十足的呢!尤其是那些双系统平板,它们不仅兼容了...
安卓14系统上线时间,七大亮点... 哎呀呀,你知道吗?最近安卓系统又来了一场大变身,安卓14系统正式上线啦!这可是科技圈的大事,咱们得好...
安卓子系统消息机制,Handl... 你有没有想过,你的安卓手机里竟然隐藏着一个神秘的子系统?没错,就是安卓子系统!它就像一个隐形的助手,...
安卓系统隐藏彩蛋9.0,体验趣... 哇,你知道吗?安卓系统里竟然藏着许多隐藏彩蛋,就像宝藏一样等着我们去发掘。今天,就让我带你一起探索安...
苹果安卓系统销量,Harmon... 你有没有发现,最近手机圈里可是热闹非凡呢!苹果和安卓两大巨头,又来了一场精彩绝伦的较量。咱们今天就聊...
安卓系统权限在哪里,安卓系统权... 亲爱的手机控们,你是否曾好奇过,那些在我们手机里默默守护我们的安卓系统权限,究竟藏在哪里呢?别急,今...
安卓手机老是系统自,不同手机系... 手机里的安卓系统是不是总感觉有点儿“闹腾”?时不时地来个“系统自启动”,让你摸不着头脑,是不是觉得这...
幻13装安卓系统,畅享智能新体... 亲爱的读者们,你是否曾对平板电脑的操作系统产生过好奇?想象一台轻薄如纸的平板,搭载了全新的安卓系统,...