For Christmas, dress up your JavaScript code as a Christmas tree.
If the effect, you can take a look at our company's official website http://www.souche.com), The js Code involved in today most of the temporary replacement into the Christmas tree, open each js Code to see the effect.
In fact, it is not amazing. We use a node. js library written by ourselves. To achieve this effect, you only need to follow the method described in the first chapter below. You can also compress code online: http://f2e.souche.com/cheniu/js2image.html
The following sections describe how to use the js2image Library and the js2image library.
Use js2image
Github: https://github.com/xinyu198736/js2image welcome to star or follow.
Js2image has two special features:
The compressed examples show that these js files are from the souche official website ):
-
Http://assets.souche.com/assets/js/souche.js souche main script
-
Http://assets.souche.com/assets/js/lib/jquery-1.7.1.min.js jquery 1.7.1
-
Http://assets.souche.com/assets/js/lib/mustache.js (mustache)
The usage is simple:
- npm install js2image -g;
Run the following command in the js Folder:
- js2image -s ./resource/jquery.js
Or execute the command with caution for all js files in a directory). It will traverse all js files in this directory in depth and compress the results file with the. xmas. js suffix.
- js2image -s ./resource/
You can generate a corresponding **. xmas. js file.
To integrate js2image into gulp or other nodes projects, you can use the module form:
- Var Js2Image = require ("js2image"); // obtain the result of codeJs2Image. getCode (". /resource/jquery. js ",". /resource/tree.png ",{}). then (function (code ){
- Console. log (code );
- })
For more information, refer to the documentation on github.
If you only want to use this effect, you can see it here. The following describes the principles of this library, and may be bypassed in some places.
Js2image implementation principle
The implementation of js2image has only three main points.
If you have some ideas, you can see that you have basically understood what is going on. The three key points are explained in detail below.
① Generate 2 Characters worth painting from the image
Here we use a ready-made npm package: image-to-ascii. This library uses specified characters to restore an image. And we use this library to generate☃The characters and spaces respectively represent the black and white characters, and then each line of the character painting is divided into an element of the array for use in the second step. This is a struct generated in the middle, for code, see utils/image-to-struct.js
② Split the js source code into small pieces as much as possible.
This is a very important step. How many small pieces of js code can be divided?
See the following code:
- !function
- (e,t
- ){ (
- "objec"
- +"t") ==
- typeof
- module && (
- "objec"+"t")
- == typeof module
- .exports?module.
- exports=e.document?t(e
- ,!0):function(e){if(!e.
- document) throw new Error (
- ("jQuer"+"y req"+"uires"+" a wi"
- +"ndow "+"with "+"a doc"+"ument") )
- ; return t (e)}:t(e)}( ("undef"+"ined")
- !=typeof window ?window:this,function(e,t){var
This is a piece of code starting with jQuery. We can see that most operators allow any number of spaces or line breaks to be inserted in the middle. We use this feature to unlink the js Code, then splice the image into any shape.
The core code is actually a regular expression. We use this regular expression to deconstruct the js source code into an array. Then, based on the number of characters required for each line, we will continue to extract fragments from the array and splice them.
- // Separate the code, which can be split into arrays in units. Var lines = hold_code.replace (/([^ a-zA-Z_0-9 =! | & $])/G, "/n $1/n"). split ("/n ");
- // With this lines array, it is easy to follow. Based on the struct generated in the first step, the Code extracted from lines is continuously traversed and filled into the struct to generate the final code:
- While (lines. length> 0 ){
- // Cyclically populate the Code with struct
- Struct. forEach (function (s ){
- Var chars_arr = s. replace (// +/g, ""); // a row with multiple groups separated *****
- Var r = s;
- Chars_arr.split (//). forEach (function (chars ){
- If (chars. length = 0 ){
- Return;
- }
- Var char_count = chars. length;
- // The code that extracts the char_count quantity from lines to fill in. This is not necessarily accurate. Ensure that the broken line is correct.
- Var l = pickFromLines (lines, char_count );
-
- R = r. replace (chars, function (){
- Return l;
- })
- })
- Result + = r + "/n"
- })
-
- }
③ Preserve the inseparable syntax
Note: At this step, it is still very early that the code you break down cannot run. Many codes that cannot wrap or add spaces are separated by you, and errors will naturally occur, how can we deal with these situations?
In this step, we will do the following:
Before code splitting, extract all the inseparable syntaxes in the code, keep them in an object, and replace these syntaxes with placeholders in the source code, then let the placeholder participate in the separation of the previous step. Because the placeholder is a complete concatenation variable, it will not be split. After the split, we can replace these placeholders.
However, in js, which syntaxes must be connected together to run normally?
Here is a summary:
- var double_operator = ["==", ">=", "<=", "+=", "-=", "*=", "/=", "%=", "++", "--", "&&", "||", ">>", "<<"]
- var three_operator = ['===', '!==']
Some fixed syntaxes can be expressed in regular expressions as follows:
- Var reg_operator = [
- {
- Start: "return ",
- Reg:/^ return [^ a-zA-Z_0-1 "'] [a-zA-Z_0-1.] +/
- // Return 0.1, return function, or return aaabb
- },
- {
- Start: "return /"",
- Reg:/^ return ".*? "// Return" d "or return ""
- },
- {
- Start: "return /'",
- Reg:/^ return '.*? '// Return 'D' or return''
- },
- {
- Start: "throw ",
- Reg:/^ throw [a-zA-Z_0-1] +? /// Throw new or throw obj
- }
- ]
Decimal point syntax, for example, 0.01 because we used Dot numbers to separate code before, but the dot numbers here cannot be used as delimiters. We need to keep the front and back numbers and the dot numbers in other syntaxes in one row, for example, value ++ and other syntaxes are inseparable between variables and operators. How can we parse these syntaxes from the source code and then process them?
Core code is in utils/keep-line.js
In fact, the core algorithm is completed by traversing a string. Then, when traversing each character, it will determine whether to enter a logic for Skip processing.
For example, if the current double quotation marks are found, the string extraction logic is entered and the traversal continues until the end of the string.
Other operators are similar to regular expression algorithms, but many details need to be processed, such as escape characters.
Some special characters, such as decimal point syntax extraction. After judging that the current character is a point number, you need to search for numbers both forward and backward, and then find out the entire syntax.
Here is not detailed, In the keep-line.js this file again a large pile of code to do this thing.
④ String deconstruct
In this step, the results are quite good, and the code can be run. However, some strings in the Code are long and they will always be retained in one line, in this way, it will affect the accuracy of the edge of some patterns. The principle of code separation is that the finer the better, it is for this consideration ).
What should we do? It is to deconstruct the string and separate the string into small pieces in five units.
There are two important issues to address;
Conclusion
Now, the entire application is complete, and the graphic code can be generated from any js and image.
Again Project Open Source Address: https://github.com/xinyu198736/js2image welcome star, By the way follow under the landlord will be more happy.