I am participating in the Mid-Autumn Festival Creative Submission contest, please see: Mid-Autumn Festival Creative Submission Contest for details

Hello everyone, I am a bowl of zhou, not you think of the “bowl of porridge”, is a front-end do not want to be drunk 👨🏻💻, if I write an article lucky can get your favor, very lucky ~

Start of the text ~

Leader: Xiao Zhou, the Mid-Autumn Festival is only ten days away. Please draw a picture of Chang ‘e flying to the moon on the console panel of our website. We can enjoy the popularity of the Festival.

I:? Console panel drawing chang ‘e flying to the moon?

Leader: Yes, it’s up to you.

Me: Ok, ok (Heart: Can you still operate this way? Ok, go research how to make it happen, don’t keep me from fishing).

The console object

The console.log() method in the console object is one of the tools we use every day as front-end developers.

In addition to the log() method, console objects also have console.info(), console.warn(), and console.error methods. These methods are basically of the same type, but the difference is that the output content type is different.

In addition to the simple ones above, there are several more interesting methods.

Print form

There is a table() method in the console object that takes one necessary parameter, either an array or an object, and the final result is displayed as a table.

The following code shows the use of console.table() :

var arr = [
    { name: 'Joe'.age: 18.sex: 'male' },
    { name: 'bill'.age: 19.sex: 'male' },
    { name: 'Cathy'.age: 20.sex: 'male'},]console.table(arr)
Copy the code

The code run result is as follows:

grouping

When we need to print a lot of information, there may be too much data on the page to locate the information we want quickly and accurately. The Console object provides two sets of methods to help with this grouping, as follows:

  • The console. Group () and the console. GroudEnd ()

  • The console. GroupCollapsed () and the console. GroudEnd ()

The difference between the two is that the former group is expanded by default, while the latter collapses by default.

Console. group() and console.groupCollapsed() accept a parameter indicating group names. Console. groudEnd() indicates that the current grouping is over.

The following shows the use of grouping:

// Expand by default
console.group('person')
console.log('name: zhang SAN')
console.log('age: 18')
console.groupEnd()
// Default collapse
console.groupCollapsed('person')
console.log('name: zhang SAN')
console.log('age: 18')
console.groupEnd()
Copy the code

The code run result is as follows:

Count operations

The count() method in the console object can be used to count. This method takes an optional argument, the output, which defaults to default. The method can also count separately according to different parameters.

The following code shows the use of console.count() :

// Default parameters
console.count()
console.count()
console.count()
// Count according to different parameters
console.count('Bowl Week')
console.count('happy coding')
console.count('Bowl Week')
console.count('happy coding')
console.count('Bowl Week')
console.count('happy coding')
Copy the code

The code run result is as follows:

Style beautification

We can also beautify the output of console.log(), which is mostly done with %c.

Let’s take a look at the Console panel in the Nuggets browser plugin:

We can see that this style is different from the default, and the code for this effect actually looks like this:

console.log('%cHi! I am the product manager of nuggets plugins, \n as a former developer, I am very happy to meet you in this way, \n if you have any jokes or good ideas about plugins to share..'line-height: 30px')
console.log('Welcome to send me an email exchange: %[email protected]'.'line-height: 30px; color: red')
Copy the code

Let’s parse this syntax now, as shown below:

When %c is encountered, the following style will be used as the style of the text after % C, and the next % C will end, and the next % C can also write CSS style at the position of the next parameter, and so on.

The following code shows multiple %c’s in a single sentence:

console.log('%c red % C blue % C green '.'color: red; '.'color: blue; '.'color: green; ')
Copy the code

The code run result is as follows:

The CSS properties allowed by console are limited. For details, see MDN

If you want to set multiple attributes, the effect is not easy to read by writing them directly as a string. Instead, you can write each item as an array and join it using the join() method, as shown in the following example:

// Place the CSS properties in an array and join them into a string
const styles = [
    'color: red'.'background: yellow'.'font-size: 24px',
].join('; ')
console.log('%cHello a bowl week ', styles)
Copy the code

Painting Chang ‘e flying to the moon

After the previous supplement and review of the console object, there are two options for drawing chang ‘e flying to the moon, as follows:

  • Using pictures directly

  • The way to achieve character painting

Now we are implementing it in two different ways.

Introduce images in the Console panel

We have learned that we can set CSS properties by % C, which supports background properties. We can introduce the picture of Chang ‘e flying to the moon as the background image, and the implementation code is shown as follows:

console.log('%c'."background-image: url('/image/change_small.png'); background-size:100%;")
Copy the code

Ideally, the following image should appear in the console panel

This image may not be displayed due to browser compatibility issues

A compatible Chang ‘e moon

Because there are compatibility problems in using pictures directly, here we draw chang ‘e flying to the moon in the way of character painting.

First of all, we introduce an image in the way of JS. The code is as follows:

let img = new Image()
img.src = './image/change_small.png'
img.onload = () = > {
    // The image is loaded and executed
}
Copy the code

Second, we need to define the

element, which does not need to be displayed, to lay the groundwork for getting pixels from canvas:

<canvas id="canvas" hidden></canvas>
Copy the code

Third, define an element that renders the image

and returns all pixels

function getPixelData() {
    const canvas = document.getElementById('canvas')
    canvas.width = img.width
    canvas.height = img.height
    const ctx = canvas.getContext('2d')
    // Draw img into the Canvas container
    ctx.drawImage(img, 0.0, img.width, img.height)
    // Get pixel data, which is a two-dimensional array, the first representing how many pixels are high, and the second representing pixels in the width
    return ctx.getImageData(0.0, img.width, img.height).data

}
Copy the code

The fourth step, according to the color of the pixel to determine what string to join, the function is as follows:

// Concatenate pixel data into characters
function joinStringDraw(pixel) {
    // Define an empty string to store our character drawing
    let str = ' '
    // Define a step size, because a pixel is converted to a character when it is converted to a character. The default size of a character is 14 pixels, which means that if the step size is 1, the image is enlarged by 14 times
    let step = 4
    // Get each pixel with a double for loop
    for (let h = 0; h < img.height; h += step) {
        str += '\n'
        for (let w = 0; w < img.width; w += step) {
            // The reason for prefilling a space here is because the height of a character is usually twice the width, so the purpose here is to increase the width of the character
            str += ' '
            // Get the RGB value of a pixel
            let pos = (h * img.width + w) * 4,
                r = pixel[pos],
                g = pixel[pos + 1],
                b = pixel[pos + 2]
            // The transparent pixels here will be identified as solid black, i.e. RBG (0, 0, 0), fill with a ● as long as they are not black, and fill with Spaces for the black areas
            str += [r, g, b].join(' ')! = ='000' ? The '*' : ' '}}return str
}
Copy the code

Step 5: Write a function to execute after the image is loaded:

img.onload = () = > {
    // Get pixel data
    const pixelData = getPixelData()
    // Splice character drawing
    const str = joinStringDraw(pixelData)
    Print the final STR
    console.log(str)
}
Copy the code

The final operation solution is as follows:

Now can rest assured to touch the fish, ha ha ha ~~

Write in the last

The story in this article is pure fiction, and the main purpose of this article is to reinforce the Console object, which is an important object in front-end development.

Since everyone finished watching, welcome to like the message, thank you.

This article was originally published in the Nuggets