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

点击免费下载源码

相关内容

热门资讯

边锋杭麻圈安卓系统,边锋科技引... 你有没有听说过边锋杭麻圈安卓系统?这可是最近在游戏圈里火得一塌糊涂的存在哦!想象你正坐在家里,手握着...
ios系统能转移到安卓系统,轻... 你有没有想过,有一天你的手机从iOS系统跳转到安卓系统,会是怎样的体验呢?这可不是天方夜谭,随着科技...
安卓系统网络连接查看,安卓系统... 你有没有遇到过这种情况:手机里装了各种APP,可就是不知道哪个在偷偷消耗着你的流量?别急,今天就来教...
什么安卓系统优化的好,打造流畅... 你有没有发现,手机用久了,就像人一样,会变得有些“臃肿”呢?尤其是安卓系统,有时候感觉就像一个老态龙...
手机安卓系统ios系统怎么安装... 你有没有发现,现在手机里的软件真是五花八门,让人眼花缭乱?无论是安卓系统还是iOS系统,都能轻松安装...
按音量键报警安卓系统,安卓系统... 你有没有遇到过这种情况:手机突然发出刺耳的警报声,吓得你心跳加速,还以为发生了什么大事?别担心,今天...
安卓系统改win版系统怎么安装... 你有没有想过,把你的安卓手机换成Windows系统的电脑呢?想象那流畅的触控体验和强大的办公功能,是...
安卓系统如何备份到苹果,轻松实... 你是不是也有过这样的烦恼:手机里的照片、联系人、应用数据等等,突然间就消失得无影无踪?别担心,今天就...
修改安卓系统参数设置,安卓系统... 你有没有发现,你的安卓手机有时候就像一个不听话的小孩子,总是按照自己的节奏来,让你有点头疼?别急,今...
安卓手机gps定位系统,畅享智... 你有没有发现,现在不管走到哪里,手机都能帮你找到路?这都得归功于安卓手机的GPS定位系统。想象你站在...
华为不能安卓系统升级,探索创新... 你知道吗?最近有个大新闻在科技圈里炸开了锅,那就是华为的新款手机竟然不能升级安卓系统了!这可真是让人...
汽车加装安卓系统卡住,探究原因... 你有没有遇到过这样的尴尬情况:汽车加装了安卓系统,结果屏幕突然卡住了,就像被施了魔法一样,怎么也动弹...
电量壁纸安卓系统下载,打造个性... 手机电量告急,是不是又得赶紧找充电宝了?别急,今天就来给你安利一款超实用的电量壁纸,让你的安卓手机瞬...
iPhonex里面是安卓系统,... 你有没有想过,那个我们每天都离不开的iPhone,里面竟然可能是安卓系统?是的,你没听错,就是那个以...
ios系统比安卓系统好在哪里,... 你有没有想过,为什么有些人对iOS系统情有独钟,而有些人却对安卓系统爱不释手呢?今天,就让我带你从多...
安卓系统跟踪设置大小,跟踪设置... 你知道吗?现在智能手机几乎成了我们生活的必需品,而安卓系统作为全球最受欢迎的操作系统之一,它的跟踪设...
在线迎新系统下载安卓,轻松开启... 你有没有想过,开学季的到来,就像一场盛大的狂欢,而在这个狂欢中,有一个小助手,它默默地守护着你的入学...
安卓系统怎么申请微信号,一键申... 你有没有想过,在安卓手机上申请一个微信账号,竟然也能变得如此简单?没错,就是那个我们每天离不开的社交...
安卓手机系统里怎么清理,轻松优... 手机里的东西越来越多,是不是感觉安卓手机系统越来越慢了呢?别急,今天就来教你怎么清理安卓手机系统,让...
安卓系统改定位地址软件,轻松掌... 你是不是也和我一样,有时候想换个角度看世界,但又不想真的搬家?别急,今天就来给你揭秘一个神奇的小工具...