Use an open-source project to turn your JavaScript into a Christmas tree! For more information, see the official website of our company. Most of the js Code involved is temporarily replaced with a Christmas tree today. 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. Of course, you can also compress the code online. We use a node. js library written by yourself. To achieve this effect, you only need to follow the method described in the first chapter below. Of course, you can also compress the code online:
The following sections describe how to use the js2image Library and the js2image library.
Use js2image
Js2image has two special features:
Compress any js source code into the final code that is stacked with code into a graph. For example, the Christmas tree, Santa Claus, codes and images can be customized.
Although the compressed js code format is damaged, it can still be run. This is the key point!
The usage is simple:
npm install js2image -g;
Run the following command in the js Folder:
js2image -s ./resource/jquery.js
Or execute all js files in a directory (with caution). 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.
Generate a character painting from an image, which has a ready-made library.
Split the js Code into a small part, as small as possible, and then replace it with the character painting generated in the previous step by line filling.
JavaScript code has a lot of non-separated syntaxes. These syntaxes should be kept in one block when it is segmented. This is the difficulty of this library, and it is also the most code around.
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. We use this library to generate a character painting that uses characters and spaces to represent the black and white characters respectively. Then, each line of the character painting is decomposed into an array element for the second step, this is a struct generated in the middle, the code can be found in 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"); // after having the lines array, it will be simple, based on the struct generated in the first step, the final code is generated by continuously traversing the code extracted from lines and filling it into struct: while (lines. length> 0) {// enter the code struct into struct cyclically. forEach (function (s) {var chars_arr = s. replace (/+/g, ""); // a row with multiple groups of 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. Make sure 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:
A string cannot be separated by double quotation marks.
It is difficult to process the escaping in an absolutely inseparable regular expression, which is a difficulty in this algorithm.
The operation operator contains 2 to 3 characters, for example, the following two types
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 edges of some patterns (the finer the code separation principle is, 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;
How to handle escape characters in a string, there are some special characters, such as 0 × 01, which cannot be separated into different strings, therefore, the integrity of these strings must be retained during separation.
The string is separated into a small string and then spliced with the plus sign. But pay attention to the operator priority. Therefore, all separated strings must be enclosed in parentheses, so that the priority of this plus sign is always the highest.
For more information about the algorithm, see splitDoubleQuot in the keep-line.js ).
Conclusion
Now, the entire application is complete, and the graphic code can be generated from any js and image.
The above shows you how to write JavaScript code into the details of the Christmas tree. For more information, see other related articles in the first PHP community!