How to be a good programmer?


When it comes to the topic of flirting with girls, it’s estimated that many people don’t feel like programmers. Most people’s impression of programmers is like this: dull, honest, introverted and unsocial. Only code in eyes, not romantic! As a veteran programmer for many years, I decided to clarify this rumor for the majority of programmers and tell you that our programmers are also very romantic!

How to be a good programmer?

In order not to let you lose the heart of the goddess, I made a confession artifact, here to share with you programmer brothers! Finally win Bai Fumei and go to the peak of life!

How to be a good programmer?

First look at the effect. Scan the QR code below to preview

How to be a good programmer?

[look at the implementation of the code]

1、 The first thing to consider before writing code is the following

  1. Compatible with different mobile phone resolutions
  2. Using CSS3 animation, more fluent
  3. An algorithm is used to locate the text and display it in the center
  4. Expansibility in later stage

2、 Tools and methods of code

We need some tools and methods to extract them for public use. It’s better not to pollute the business code. The word “pollution” is used here. When we do projects, in fact, many of the codes are unrelated to the business. If they are all written together, it will make our business very unclear. The reason why we need to extract them is that we need to extract them, It’s to make our business logic clear. When you pull it out, you will find that the business code is just a few lines, which looks very concise.

Here is the non business code I pulled out

 *@ desc generates a random number in the specified range
 * @param  {Number} min
 * @param  {Number} max
 * @return {Number}
export function randomNum(min, max) {
    return Math.floor(min + Math.random() * (max - min));

 *The @ desc array is out of order
export function randomArrSort(arr) {
    arr.sort(() => 0.5 - Math.random());
    return arr;

 *@ desc randomly generates colors
 * @return {String}
export function randomColor() {
    return '#' + ('00000' + ((Math.random() * 0x1000000) << 0).toString(16)).slice(-6);

 *Generate an ID with no duplicate
export function getRandomID(randomLength = 8) {
    return 'id_' + Number(
            .substr(3, randomLength || 8) +

 *@ desc set auto fit size
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;
        left: (innerWidth - width * scale) / 2,
        top: top,
        transform: `scale(${scale})`

 *@ desc calculates sacle and offset
export function getScale() {
    const width = 320;
    const height = 514;
    //Automatic adaptation
    const { innerWidth, innerHeight } = window;
    //Suppose the width adaptation scale * width = innerwidth
    let scale1 = innerWidth / width;
    //Assume that the height of scale * height = innerhigh
    let scale2 = innerHeight / height;
    return scale1 > scale2 ? scale2 : scale1;

3、 Extract public classes

In fact, our text can be separated into a class for management. This class needs to contain some methods related to text

1. Get random copy
2. Get all text
3. Render all text
4. Execute text animation
5. Calculate the location of the target copy
6. Find the location of the target text, and then clone one
7. Initialization
8. Reexecution

I have roughly assessed the need for these methods.

So the class structure of characters is as follows:

import * as tool from '../utils/tools';

import { texts } from './texts';

 *How to use @ desc text
export default class Text {
    constructor(set) {
        this.set = Object.assign(
                target: '#phone',
                width: 320,
                height: 514,
                callback: () => {}
        this.dom = $(;

    //Get random copy
    getText() {
        const index = tool.randomNum(0, texts.length - 1);
        const t1 = texts[index];
        return t1.split('');

    //Get all text
    getAllText() {
        let all = [];
        const { width, height } = this.set;
        texts.forEach(d => {
            // let str = d.replace(/[,,。,?,!,……,~,:”,“,\s]/gm, '');
            all = [...all, ...d.split('')];
        //De duplication
        all = Array.from(new Set(all));
        all = => {
            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,
                width: a,
                height: a,
        return tool.randomArrSort(all);

    //Render 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>`;

    //Calculates the position of the target text
    getTargetCoord(targetText) {
        const tlen = targetText.length;
        let val = 10; //  10 line breaks
        let size = 20,
            arr = [],
            boxWidth = Math.ceil(tlen / val) * size,
            boxHeight = size * val; //  10 word line feed
        const { width, height } = this.set;
        //Coordinate starting point
        const start = {
            x: (width - boxWidth) / 2,
            y: (height - boxHeight) / 2 - 100
        for (let i = 0; i < tlen; i++) {
            let a = Math.floor(i / val);
                width: size,
                height: size,
                x: start.x + a * size,
                y: start.y + (i - a * val) * size
        return arr;

    //Find the corresponding word and clone an object
    cloneTargetStyle(d, tArr) {
        const obj = tArr.filter(a => {
            return a.text === d;
        })[0]; = tool.getRandomID();
        return { ...obj };

    //Target text animation
    targetTextAimate() {
        let index = 0;
        let tArr = [];
        this.allText.forEach(d => {
            if (d.iskey) {
                opacity: 0

        //Get target array
        const targetArr = [];
        this.targetText.forEach(d => {
            targetArr.push(this.cloneTargetStyle(d, tArr));

        //Set coordinates
        const arr = this.getTargetCoord(targetArr);
        //Render DOM
        targetArr.forEach((d, index) => {
            let item = arr[index];
                opacity: 1,
                width: item.width,
                height: item.height,
                transform: `translate(${item.x}px, ${item.y}px) scale(1)`

        setTimeout(() => {
        }, 3000);

    //Alltext text text animation
    allTextAnimate() {
        const { width, height } = this.set;
        let count = 0;
        const doAnimate = () => {
            this.allText = => {
                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;
                    transform: `translate(${x}px, ${y}px) scale(${scale})`
        const runTime = () => {
            if (count > 2) {
                setTimeout(() => {
                }, 3000);
            setTimeout(() => {
            }, 3000);

    restart = () => {
        this.targetText = this.getText();
        this.allText = this.getAllText.bind(this)();
        setTimeout(() => {
        }, 10);

    init = () => {
        //Get copy
        this.targetText = this.getText();
        this.allText = this.getAllText.bind(this)();

        //Render text

        setTimeout(() => {
        }, 0);

4、 Copywriting is extensible and can be customized

In order to customize the copy, I took out the copy separately

export const texts = [
    'I want to buy a piece of land from you. What land to buy? Buy your heart and soul,
    'Do you know the difference between you and the stars? The stars are in the sky and you are in my heart,
    'I'm sure I'll just need a kiss.',
    'loveliness is not a long-term solution, loveliness I am',
    Piggy page, you deserve me.
    'There's a rumor that I like you. Let me clarify. It's not a rumor ',
    "Only the state officials are allowed to set fire, and you are not allowed to leave me.",
    You should have been very tired last night, because you kept running in my dream,
    'I think you are hurting me when you approach me. I like you so much.',
    'you are so strange and lovely today',
    'I think I'm so playful. I like the way you look every day.',
    'Do you have a lighter? No, How do you light my heart,
    'I can't tell why I love you. I only know that as long as I have you, I can't fall in love with others',
    'I like you, like your mother beat you, unreasonable',
    'Do you know why you are so cold? Because you don't have a warm partner like me,
    I like you very much,
    Confucius said, "think twice before you leap, 1, 2, 3 ~ um ~ I like you.",
    "If you're not talented, you'll find yourself short of me.",
    'Do you have a map? I'm lost in your eyes,
    'Do you know what God I like best? It's your eyes,
    If you are ugly, I might take you shopping, watching movies, eating western food, taking a walk, watching the stars and the moon, from poetry to Philosophy of life, but you are so beautiful that I just want to fall in love with you,
    "My rent is due. Can I live in your heart?",
    'if I had a baby with you, what do you think he would be“ What seat? Gemini“ No, our masterpiece. "',
    "Can you smile?"“ Why? "“ Because I forgot sugar in my coffee,
    'what would you like to drink“ I want to take care of you,
    I think you look like a relative of mine“ My mother's daughter-in-law,
    'Do you know what's in the eye of the beholder“ Sishi. "“ No, there you are. "',
    'have you been fat again recently“ No, why do you say that? "“ Then why do you weigh more and more in my heart,
    'the fallen leaves return to their roots, you belong to me. ',
    'the sea of bitterness is endless, and it's me who comes back. '",
    'I don't want to hit the south wall. I just want to hit my husband's chest.',
    You must have been a carbonated drink in your last life, otherwise how could I bubble happily when I saw you,
    'can you play the piano? can't? How do you touch my heart,
    The first time I saw you, God said a few words in my ear. I was doomed,
    'Do you know what kind of wine is the easiest to get drunk? It's yours forever,
    'what do you belong to“ I'm a tiger. "“ Don't cheat any more. You belong to me,
    'what constellation are you? Gemini? "“ no I made it for you,
    'Do you know what my biggest weakness is? It's you,
    'if I push you into the garden, I won't find you. Because you are as beautiful as a flower,
    'sometimes life is a little miserable. Don't complain. Just hold me. '

5、 Business code

In fact, when we extract classes, we extract non business related public methods. The business code is very simple. Here is the HTML + business-related code.

<!DOCTYPE html>
<html lang="zh-cn">

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- <script></script> -->

    <!--[if lt IE 10]>
<p class="browse-tips">
    You are using the < strong > outdated < / strong > browser. Please '> update the browser < / a > to ensure a good user experience.
    <div class="logo">
        <span>Provided by, an open source H5 editor</span>
    <div id="app">
        <div class="title" id="title">
            < button id = "run" > generate love words < / button >
        <div id="phone">
        <div class="qrcodebox">
            <div id="qrcode">
            < button id = "restart" > play again < / button >
            < button id = "saveimg" > generate image < / button >
import * as tool from '../utils/tools';

import Text from './Text';
import domtoimage from 'dom-to-image';

//Set size
function setSize() {
    const scale = tool.getScale();
    tool.setSize($('#app'), scale);

$(function() {

    $(window).resize(() => {

        .each(function() {
                'animation-delay': `${Math.random()}s`

    setTimeout(() => {
    }, 2000);

    const textAnim = new Text({
        target: '#phone',
        callback: () => {

    $('#run').on('click', () => {

    $('#restart').on('click', () => {

    //Save map
    $('#saveImg').on('click', () => {
            .then(function(dataUrl) {
                $('body').append(`<img id="toimg" />`);
                Alert ('the picture has been generated, long press the screen to save it to the phone!)
            .catch(function(error) {
                console.error('oops, something went wrong!', error);

6、 Summary

When we do a project, we try our best to separate out the code unrelated to the business and make the programming idea as clear as possible. The design of any API interface is to enable users to better realize their business. Of course, if you are interested in the underlying implementation logic, you can also understand the internal implementation of each method, Further enhance their own strength, of course, the text class can also be further optimized, such as the data as a parameter to the class, which will be more flexible! These are the so-called optimization and iteration.

Finally, as a programmer, no matter how busy your work is, please don’t forget to tease my sister. I wish you all an early order! Address of GitHub:…