For Christmas, dress up your JavaScript code as a Christmas tree.

Source: Internet
Author: User

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.

  • Github address: https://github.com/xinyu198736/js2image ps: star

  • Online conversion address: http://f2e.souche.com/cheniu/js2image.html

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:

 
 
  1. npm install js2image -g; 

Run the following command in the js Folder:

 
 
  1. 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.

 
 
  1. 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:

 
 
  1. Var Js2Image = require ("js2image"); // obtain the result of codeJs2Image. getCode (". /resource/jquery. js ",". /resource/tree.png ",{}). then (function (code ){
  2. Console. log (code );
  3. })

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:

 
 
  1.                         !function             
  2.                         (e,t             
  3.                         ){ (             
  4.                        "objec"           
  5.                       +"t")  ==           
  6.                      typeof           
  7.                    module &&  (         
  8.                   "objec"+"t")           
  9.                 == typeof module         
  10.               .exports?module.       
  11.             exports=e.document?t(e       
  12.           ,!0):function(e){if(!e.     
  13.         document) throw new Error (     
  14.       ("jQuer"+"y req"+"uires"+" a wi"   
  15.    +"ndow "+"with "+"a doc"+"ument") )   
  16. ; return t (e)}:t(e)}( ("undef"+"ined") 
  17. !=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.

 
 
  1. // 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 ");
  2. // 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:
  3. While (lines. length> 0 ){
  4. // Cyclically populate the Code with struct
  5. Struct. forEach (function (s ){
  6. Var chars_arr = s. replace (// +/g, ""); // a row with multiple groups separated *****
  7. Var r = s;
  8. Chars_arr.split (//). forEach (function (chars ){
  9. If (chars. length = 0 ){
  10. Return;
  11. }
  12. Var char_count = chars. length;
  13. // 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.
  14. Var l = pickFromLines (lines, char_count );
  15.  
  16. R = r. replace (chars, function (){
  17. Return l;
  18. })
  19. })
  20. Result + = r + "/n"
  21. })
  22.  
  23. }

③ 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:

 
 
  1. var double_operator = ["==", ">=", "<=", "+=", "-=", "*=", "/=", "%=", "++", "--", "&&", "||", ">>", "<<"]  
  2. var three_operator = ['===', '!=='] 

Some fixed syntaxes can be expressed in regular expressions as follows:

 
 
  1. Var reg_operator = [
  2. {
  3. Start: "return ",
  4. Reg:/^ return [^ a-zA-Z_0-1 "'] [a-zA-Z_0-1.] +/
  5. // Return 0.1, return function, or return aaabb
  6. },
  7. {
  8. Start: "return /"",
  9. Reg:/^ return ".*? "// Return" d "or return ""
  10. },
  11. {
  12. Start: "return /'",
  13. Reg:/^ return '.*? '// Return 'D' or return''
  14. },
  15. {
  16. Start: "throw ",
  17. Reg:/^ throw [a-zA-Z_0-1] +? /// Throw new or throw obj
  18. }
  19. ]

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.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.