说到撩妹这个话题,预计许多人都以为和程序员沾不上边,大多数人对程序员的印象是如许的:木讷,忠实,内向,不爱交际。眼里只需代码,不懂浪漫!作为一个多年的程序员老砖员,我决定为宽大程序员同伴廓清这个流言,通知人人,我们程序员也是很浪漫的!
为了不让人人痛失女神的芳心,我做了一个表白神器,在此和列位程序员小哥哥们分享分享!终究赢取白富美,走上人生顶峰!
起首看看结果。扫描下方二维码即可预览
【看看代码的完成】
一、写代码前起首须要斟酌以下几点
- 兼容差别手机分辨率
- 采纳CSS3动画,更流通
- 笔墨的定位采纳一个算法,将其竖排居中显现
- 后期的可拓展性
二、代码之东西要领
我们须要一些东西要领,将之抽离出来以便公用,最好不要污染营业代码,这里用了一个词“污染”,在我们做项目的时刻,实在许多代码都是和营业无关的,假如都写到一起了,如许会让我们的营业异常不清楚,之所以要抽离出来,就是为了让我们的营业逻辑清楚可见,当抽离出来后,你会发明,营业代码就几行,看上去异常的简约。
以下是我抽离的非营业代码
/**
*
* @desc 天生指定局限随机数
* @param {Number} min
* @param {Number} max
* @return {Number}
*/
export function randomNum(min, max) {
return Math.floor(min + Math.random() * (max - min));
}
/**
* @desc 数组打乱递次
*/
export function randomArrSort(arr) {
arr.sort(() => 0.5 - Math.random());
return arr;
}
/**
*
* @desc 随机天生色彩
* @return {String}
*/
export function randomColor() {
return '#' + ('00000' + ((Math.random() * 0x1000000) << 0).toString(16)).slice(-6);
}
/**
* 天生一个用不反复的ID
*/
export function getRandomID(randomLength = 8) {
return 'id_' + Number(
Math.random()
.toString()
.substr(3, randomLength || 8) + Date.now()
).toString(36);
}
/**
* @desc 设置自动适配的尺寸
*/
export function setSize($box, scale, fixed) {
let width = fixed ? appWidth : $box.width(),
height = fixed ? appHeight : $box.height();
const { innerWidth, innerHeight } = window;
let top = (innerHeight - height * scale) / 2;
if (top < 0) {
top = 0;
}
$box.css({
left: (innerWidth - width * scale) / 2,
top: top,
transform: `scale(${scale})`
});
}
/**
* @desc 盘算sacle 和 偏移
*/
export function getScale() {
const width = 320;
const height = 514;
// 自动适配
const { innerWidth, innerHeight } = window;
// 假定宽度适配 scale * width = innerWidth
let scale1 = innerWidth / width;
// 假定高度适配 scale * height = innerHeigh
let scale2 = innerHeight / height;
return scale1 > scale2 ? scale2 : scale1;
}
三、抽取大众类
实在我们的笔墨能够零丁抽离成一个类举行治理,这个类须要包括笔墨相干的一些要领
1、猎取随机案牍
2、猎取悉数笔墨
3、衬着悉数的笔墨
4、实行笔墨动画
5、盘算目的案牍的位置
6、寻觅目的笔墨的位置,然后clone一个
7、初始化
8、从新实行
我大抵评价了,须要这些要领。
所以笔墨的类组织以下:
import * as tool from '../utils/tools';
import { texts } from './texts';
/**
* @desc 笔墨的要领
*/
export default class Text {
constructor(set) {
this.set = Object.assign(
{
target: '#phone',
width: 320,
height: 514,
callback: () => {}
},
set
);
this.dom = $(set.target);
}
// 猎取随机案牍
getText() {
const index = tool.randomNum(0, texts.length - 1);
const t1 = texts[index];
return t1.split('');
}
// 猎取悉数笔墨
getAllText() {
let all = [];
const { width, height } = this.set;
texts.forEach(d => {
// let str = d.replace(/[,,。,?,!,……,~,:”,“,\s]/gm, '');
all = [...all, ...d.split('')];
});
// 去重
all = Array.from(new Set(all));
all = all.map(text => {
const a = tool.randomNum(5, 10);
const iskey = this.targetText.indexOf(text) === -1 ? false : true;
return {
id: tool.getRandomID(),
y: height / 2 - a / 2,
x: width / 2 - a / 2,
opacity: Math.random() * 0.5,
scale: Math.random() * 1.2,
iskey,
width: a,
height: a,
text
};
});
return tool.randomArrSort(all);
}
// 衬着allText
renderTexts(arr) {
let shtml = '';
arr.forEach(d => {
const { id, x, y, scale, opacity, iskey, width, height, text } = d;
shtml += `<span id="${id}" class="${
iskey ? 'text text-active' : 'text'
}" style="width: ${width}px; height: ${height}px; transform: translate(${x}px, ${y}px) scale(${scale}); opacity: ${opacity};">${text}</span>`;
});
this.dom.append(shtml);
}
// 盘算目的笔墨的位置
getTargetCoord(targetText) {
const tlen = targetText.length;
let val = 10; // 10个换行
let size = 20,
arr = [],
boxWidth = Math.ceil(tlen / val) * size,
boxHeight = size * val; // 10个字换行
const { width, height } = this.set;
// 坐标出发点
const start = {
x: (width - boxWidth) / 2,
y: (height - boxHeight) / 2 - 100
};
for (let i = 0; i < tlen; i++) {
let a = Math.floor(i / val);
arr.push({
width: size,
height: size,
x: start.x + a * size,
y: start.y + (i - a * val) * size
});
}
return arr;
}
// 找到对应的字,然后clone一个对象
cloneTargetStyle(d, tArr) {
const obj = tArr.filter(a => {
return a.text === d;
})[0];
obj.id = tool.getRandomID();
return { ...obj };
}
// 目的笔墨动画
targetTextAimate() {
let index = 0;
let tArr = [];
this.allText.forEach(d => {
if (d.iskey) {
tArr.push(d);
}
$(`#${d.id}`).css({
opacity: 0
});
});
// 猎取目的数组
const targetArr = [];
this.targetText.forEach(d => {
targetArr.push(this.cloneTargetStyle(d, tArr));
});
// 设置坐标
const arr = this.getTargetCoord(targetArr);
// 衬着dom
this.renderTexts.bind(this)(targetArr);
targetArr.forEach((d, index) => {
let item = arr[index];
$(`#${d.id}`).css({
opacity: 1,
width: item.width,
height: item.height,
transform: `translate(${item.x}px, ${item.y}px) scale(1)`
});
});
setTimeout(() => {
this.set.callback();
}, 3000);
}
// allText 笔墨动画
allTextAnimate() {
const { width, height } = this.set;
let count = 0;
const doAnimate = () => {
count++;
this.allText = this.allText.map(d => {
d.y = tool.randomNum(0, height);
d.x = tool.randomNum(0, width);
d.scale = Math.random() * 1.5;
// d.opacity = Math.random() * 0.5;
return d;
});
this.allText.forEach(d => {
const { x, y, scale } = d;
$(`#${d.id}`).css({
transform: `translate(${x}px, ${y}px) scale(${scale})`
});
});
};
const runTime = () => {
if (count > 2) {
setTimeout(() => {
this.targetTextAimate.bind(this)();
}, 3000);
return;
}
setTimeout(() => {
doAnimate();
runTime();
}, 3000);
};
doAnimate();
runTime();
}
// 从新实行
restart = () => {
this.dom.empty();
this.targetText = this.getText();
this.allText = this.getAllText.bind(this)();
this.renderTexts.bind(this)(this.allText);
setTimeout(() => {
this.allTextAnimate.bind(this)();
}, 10);
};
// 初始化
init = () => {
// 猎取案牍
this.targetText = this.getText();
this.allText = this.getAllText.bind(this)();
// 衬着笔墨
this.dom.addClass('h5ds-text7');
this.renderTexts.bind(this)(this.allText);
setTimeout(() => {
this.allTextAnimate.bind(this)();
}, 0);
};
}
四、案牍拓展性,可自定义案牍
为了能够自定义案牍,我零丁把案牍拿了出来
export const texts = [
'我想在你那边买一块地。买什么地?买你的死心踏地',
'你晓得你和星星有什么区别吗?星星在天上而你在我内心',
'我万无一失 就只差你一吻了',
'可爱不是长久之计,可爱我是',
'小猪佩奇,你配我',
'有流言说我喜好你,我廓清一下,那不是流言',
'只许州官放火 不准……你脱离我',
'你昨天晚上应当很累吧,由于你在我梦里一向跑个不断',
'我以为你靠近我就是在害我,害得我好喜好你呀',
'你本日好新鲜,怪可爱的',
'我以为我好花心,你天天的模样我都好喜好',
'你有打火机嘛?没有?那你是怎样点燃我的心的',
'我说不清我为何爱你,我只晓得,只需有你,我就不能够爱上他人',
'我喜好你,像你妈打你,不讲道理',
'晓得你为何这么冷吗?由于你没有像我这么暖的对象在身旁啊。',
'无事献殷勤,非……异常喜好你',
'子曰:三思而后行,1,2,3~嗯~我喜好你。',
'小女子鄙人,掐指一算,公子此生缺我。',
'你有舆图吗?我在你的眼睛里迷路了。',
'你晓得我最喜好什么神吗?是你的眼神。',
'你如果丑点,我也许能够带你逛街看电影吃西餐散散步看星星看玉轮,从诗词歌赋谈到人生哲学,可你长的那末悦目,让我只想和你爱情。',
' 我房租到期了,能够去你内心住吗?',
'“如果我和你生一个孩子你以为他会是什么座?”“什么座?双子座?”“不,我们的佳构。”',
'“你能够笑一个吗?”“为何啊?”“由于我的咖啡忘加糖了。”',
'“你想喝点什么?”“我想庇护你。”',
'“我以为你长得像我一个亲戚。”“???”“我妈的儿媳妇。”',
'“你晓得情人眼里出什么吗?”“西施啊。”“不,涌现你。”',
'“你近来是否是又胖了?”“没有啊,为何这么说?”“那你为何在我内心的重量越来越重了呢?”',
'落恭弘=叶 恭弘归根,你归我。',
'苦海无涯,转头是我。',
'不想撞南墙了,只想撞撞教师胸膛。',
'你上辈子一定是碳酸饮料吧,不然我怎样一看到你就开心肠冒泡呢。',
'你会弹钢琴吗?不会?那你是怎样撩动我的心弦的呢。',
'第一次见到你时,天主在我耳旁说了几个字,在所难免。',
'你晓得喝什么酒最轻易醉吗?是你的天长日久。',
'“你属什么?”“我属虎。”“你不要再哄人了,你属于我。”',
'“你是什么星座? 双子座吗?”“ 不是。我是为你量身定做。”',
'你晓得我最大的瑕玷是什么吗?是瑕玷你。',
'假如我把你推到花圃内里,我就会找不到你。由于你像花儿一样优美。',
'有时刻生涯有些灾难,你不要去埋怨,抱我就好了。'
];
五、营业代码
实在当我们抽离了类,抽取了非营业相干的大众要领。营业代码就异常简朴了,下面就是HTML + 营业相干的代码。
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<title></title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<!-- <script src="https://cdn.bootcss.com/jquery.qrcode/1.0/jquery.qrcode.min.js"></script> -->
</head>
<body>
<!--[if lt IE 10]>
<p class="browse-tips">
您正在运用<strong>过期的</strong>浏览器。 请<a href='http://browsehappy.com/'>更新浏览器</a>,以保证优越的用户体验。
</p>
<![endif]-->
<div class="logo">
<span>由开源H5编辑器h5ds.com供应</span>
</div>
<div id="app">
<div class="title" id="title">
<h1>
<span>七</span>
<span>夕</span>
<span>必</span>
<span>备</span>
<span>甜</span>
<span>言</span>
<span>蜜</span>
<span>语</span>
</h1>
<button id="run">天生情话</button>
</div>
<div id="phone">
</div>
<div class="qrcodebox">
<div id="qrcode">
<img src="/assets/images/qrcode.jpg" alt="">
</div>
<br>
<button id="restart">再玩一次</button>
<br>
<button id="saveImg">天生图片</button>
</div>
</div>
</body>
</html>
import * as tool from '../utils/tools';
import Text from './Text';
import domtoimage from 'dom-to-image';
// 设置尺寸
function setSize() {
const scale = tool.getScale();
tool.setSize($('#app'), scale);
}
$(function() {
setSize();
$(window).resize(() => {
setSize();
});
$('#title')
.find('span')
.each(function() {
$(this).css({
'animation-delay': `${Math.random()}s`
});
});
setTimeout(() => {
$('#title')
.find('button')
.show();
}, 2000);
const textAnim = new Text({
target: '#phone',
callback: () => {
$('.qrcodebox').show();
}
});
// 最先
$('#run').on('click', () => {
$('#title').hide();
textAnim.init();
});
// 从新挑选
$('#restart').on('click', () => {
$('.qrcodebox').hide();
textAnim.restart();
});
// 保留图
$('#saveImg').on('click', () => {
domtoimage
.toPng($('body')[0])
.then(function(dataUrl) {
$('body').append(`<img id="toimg" src="${dataUrl}" />`);
alert('图片已天生,长按屏幕保留到手机!')
})
.catch(function(error) {
console.error('oops, something went wrong!', error);
});
});
});
六、总结
在做一个项目的时刻,我们尽量的剥离出营业不相干的代码,让编程的头脑尽量的清楚,任何API接口的设想都是为了让用户更好的完成本身的营业,固然,假如对底层的完成逻辑有兴致的朋侪,也能够去详细的了解下每一个要领内部的完成,进一步提拔本身的气力,固然,Text这个类还能够进一步的优化,比方把数据作为参数传到类内里,如许做会更天真!这些就是厥后所谓的优化,迭代环节了。