Drawing diary of a front-end engineer

The author of this article is the front-end development engineer of 360 Qiwu Troupe

As a front-end, let me first talk about how I became interested in the front-end. When I first came into contact with web page development, I found that web pages are amazing. It is very interesting and fulfilling to type a few lines of code in a text editor, change the extension, and double-click the page to display it. With your own code, you can change the color and size with one attribute, and you can make a cool special effect and so on. I saw a sentence before, saying that CSS is the web version of the four major Asian magic collections. So my sharing today starts here, and I will introduce how front-end engineers draw pictures.

On the Web, graphics are usually drawn through the browser. A modern browser is a complex system, and the part responsible for drawing graphics is the rendering engine. I have summarized the way the rendering engine draws graphics. There are generally 4 types.

1. Traditional HTML+CSS

This method is usually used to render normal web pages. In fact, the HTML and CSS performance capabilities of modern browsers are very powerful, which can fully realize conventional chart display, as well as some interesting special effects and animations. How does css paint?

Let's look at two pictures first, guess which one is drawn by css?

51683941a23752a292ab4dcb23317a88.jpeg

If you guess both, congratulations, you guessed right~ These two paintings are all written by css.

The first classical portrait of a woman (hereafter referred to simply as a dame), author Diana uses HTML and CSS to create a portrait inspired by Flemish and Baroque styles. The realization of this picture requires thousands of lines of code. She has a strict rule that all elements must be drawn manually. SVG is not used in the creation process, only Atom text editor and Chrome developer tools are used. That means she doesn't depend on libraries, shortcuts, or some kind of visual editor. That is to say, every curve and gradient, every highlight and shadow, every hair and eyelash, every piece of lace and folds on the screen is typed out from scratch with lines of code. Curves, light and shadows, gradients, each element is quite complex.
Such a degree of sophistication and creativity made netizens who study art lament that "learning to draw is worse than writing code", and students who study computer feel that "other people's writing is so artistic, it must be because my textbook is opened in the wrong way".
This project also once boarded the second place on the GitHub Trending list.

Part of the code implementation of the lady's eyelashes:0b46010af55d1280fc5cfa18a8d5b860.png

The water cup in the second picture also has the same effect. The whole article is realized by drawing border-radius, box-shadow, transform, etc. a little bit. It can be said that it is very pupil earthquake.

From the above examples, we can see that html+css can easily realize some simple graphics, but there are advantages and disadvantages:

advantage:
  1. It is very beneficial to implement some simple visual charts with CSS, which not only simplifies development, but also does not require the introduction of additional libraries, which can save resources and increase the speed of opening web pages.

  2. Understanding the drawing ideas of CSS is also very helpful for visualization. For example, many theories of CSS are related to vision, which can be used for reference in visualization.

shortcoming:
  1. HTML and CSS are mainly created for web page layout. In terms of the corresponding relationship between data and graphics, this method is not clear and the maintenance cost is high.

  2. In addition, css is part of page rendering, and changes in css may have a certain impact on performance. The things involved in css are very complicated, and the performance overhead required is relatively high, and the overhead for drawing tasks is relatively high.

  3. dom has complex support for non-rectangular elements. For example, if we need to represent circles, ellipses, straight lines, irregular polygons, etc. on the chart, the traditional DOM implementation will become more complicated. For things like pie charts and line charts, it would be more verbose to use dom element simulation alone. Even when implemented, it is very unintuitive. So this method is only suitable for some relatively simple graphics.

2.svg

There is not much difference between SVG and traditional HTML+CSS drawing methods. However, the ability of HTML elements to draw vector graphics is somewhat insufficient, and SVG just makes up for this deficiency. A simple SVG document consists of root elements and basic shape elements, such as elements used to define circular and rectangular curves, and Bezier curves can be drawn.
Let's look at a simple example, using tags:

<svg width="300" height="300" style="border: 1px solid red;">
  <circle
    cx="60"
    cy="80"
    r="50"
  >
  </circle>
</svg>

We will get a circle:
8be31ac887df655a978667ce5153bf91.png

As can be seen from the above examples, the way of drawing charts with SVG is not much different from that of HTML and CSS, except that HTML tags are replaced with SVG tags, and some special attributes supported by SVG are used. The disadvantage of HTML is that the shape of HTML elements is generally a rectangle. Although with the aid of CSS, it is also possible to draw graphics of various other shapes, even irregular graphics, but overall it is still very troublesome. SVG makes up for this deficiency, making the drawing of irregular graphics easier. Therefore, drawing with SVG is much more convenient than HTML and CSS.

advantage:

svg is an image format based on xml syntax, a bit like html.

  1. Images are vector graphics (except for inline bitmaps) and can be scaled without distortion.

  2. As a professional drawing format, it provides many graphic elements, such as circles, rectangles, curves, etc.

  3. Can be loaded with the src attribute of the img element.

  4. It can be connected in html, and can be operated through js, which is very convenient.

  5. Some CSS works on SVG elements. Many graphics libraries also use SVG as the default graphics rendering engine. Such as @antv/x6, d3 and so on.

shortcoming:
  1. Like html elements, svg needs to be parsed by the engine, calculated by the layout and generated by the renderer before outputting graphics. An SVG element only represents a basic graphic. If the displayed data is complex, there will be many SVG elements for generating graphics. There are many elements, and the performance overhead is high. A large number of SVG elements will not only take up a lot of memory space, but also increase the overhead of engine, layout calculation and rendering tree generation, reduce performance and slow down rendering speed. This means that SVG is only suitable for simple visualization scenarios with few elements.

  2. A declarative image representation like svg is not conducive to programming and detailed control, and the development cost of fine graphics and animation is relatively high.

3. canvas canvas

Different from the declarative drawing method of svg, canvas is an API provided by the browser that can directly use code to draw graphics on a flat "canvas". Using it to draw is more like traditional "writing code", simple In other words, the drawing command is called, and then the engine draws the graphics directly on the page.
That is to say, you need to tell the canvas how to draw, which is an instructional drawing system. The label is just a graphic container, which is equivalent to a canvas, and the canvas element itself has no drawing ability. All drawing work must be done inside JavaScript, which is equivalent to using a brush to draw on a canvas.

So how does Canvas draw visual charts?
  1. Canvas creates a blank canvas on the browser and gives us the ability to draw content by providing a rendering context.

getContext("2d") 对象是内建的 HTML5 对象,拥有多种绘制路径、矩形、圆形、字符以及添加图像的方法。 
getContext() 获取 canvas 的上下文环境
  1. In order to achieve more complex effects, Canvas also provides a very rich setting and drawing API, we can change the fill and stroke color by operating the context, perform geometric transformation on the canvas, call various drawing instructions, and then draw the graphics output to canvas.

canvas There are two ways to create graphics:
  1. context.fill()
    The fill() method fills the current image (path). The default color is black. Before filling, use fillStyle to set the color or gradient of the fill, and if the path is not closed, the fill() method will add a line from the end point to the start point of the path to close the path (just like closePath()) , and populate the path.

  2. context.stroke()
    The stroke() method will actually draw the path defined by the moveTo() and lineTo() methods. The default color is black. Before drawing graphics, set the drawing style

advantage:
  1. Canvas directly provides the drawing API, giving developers more capabilities and being able to directly manipulate the drawing context.

  2. At the same time, there is no more encapsulation for the encapsulation of graphics itself and event processing, and a series of operations such as HTML and CSS parsing, rendering tree construction, and layout are not required. Therefore, for simple drawing, Canvas is much faster and more efficient than HTML/CSS and SVG.

shortcoming:
  1. Canvas rendering is very efficient, but since it is an independent canvas element in the page, it is difficult for us to precisely control the local area separately like manipulating the dom. Through mathematical calculations, we can obtain local graphics by positioning, but it is troublesome.

  2. But if there are too many graphics to be drawn, or when dealing with a large number of pixel calculations, Canvas2D will still encounter performance bottlenecks.

4.webgl

webgl is the most complex drawing method, and it is a powerful drawing system provided by the browser. It is relatively complicated to use, but powerful, and can make full use of the parallel computing ability of the GPU to quickly and accurately manipulate the pixels of the image. Perform hundreds of thousands or millions of calculations at the same time. WebGL has only been developed for more than 10 years so far. But it has gone through two generations, based on the OpenGL graphics programming language, it can directly communicate with the cpu GPU, and can control every detail of the graphics output. Based on this, writing pure WebGL code is not the same as regular JavaScript, and the api is relatively More low-level, more complex, but incredibly powerful.
In theory, Canvas2D is fast enough. However, in the following situations, we need a lower-level technology, which is applicable to the following scenarios:

  1. The number of graphs drawn is very large,

  2. It is necessary to do a lot of processing on the details of the image, such as light and shadow processing, fluid effects, etc., which need to calculate a lot of pixels. Since these effects often need to accurately change all the pixels of an image in the global or local area, the number of pixels to be calculated is very large. Many (generally hundreds of thousands or even millions of orders of magnitude). At this time, even if the Canvas2D operation is adopted, the performance bottleneck will be reached.

  3. It also has built-in processing for 3D object projection, depth detection, etc., which makes it more suitable for drawing 3D scenes.

For HTML/CSS, SVG and Canvas, it is a variety of packages for GPU programs. We don't need to care about their specific underlying mechanisms, and we can directly use the tags and APIs provided by them to draw graphics. For example, we only need to understand the drawing of creating SVG elements It is stated that if you learn to execute the drawing commands corresponding to Canvas, you will be able to output graphics. But WebGL allows us to face the underlying interface directly. It can only draw basic primitives such as points, line segments, and triangles. If you want to use WebGL to complete more complex tasks, you need to provide appropriate code, and use points, lines, and triangles in combination instead. So to draw with WebGL, we have to go into the details. In other words, we have to deal with memory, GPU, and really control every detail of graphics output. Of course, there are certain libraries for encapsulating WebGL. Such as Three.JS, Babylon.js and so on. We can use them to create various 3D scenes, including various objects such as cameras, light and shadow, materials, etc., and easily realize various desired geometry.

Related articles:
Lady: https://diana-adrianne.com/purecss-francine/
Water Cup: https://codepen.io/ivorjetski/pen/xMJoYO
webgl Basics: https://juejin.cn/post/6844903478456745997

Reference article: https://zhuanlan.zhihu.com/p/201424448

- END -

About Qi Wu Troupe

Qi Wu Troupe is the largest front-end team of 360 Group, and participates in the work of W3C and ECMA members (TC39) on behalf of the group. Qi Wu Troupe attaches great importance to talent training. There are engineers, lecturers, translators, business interface people, team leaders and other development directions for employees to choose from, and supplemented by providing corresponding training on technical skills, professional skills, general skills, leadership skills, etc. course. Qi Dance Troupe welcomes all kinds of outstanding talents to pay attention to and join Qi Dance Troupe with an open and talent-seeking attitude.

7cc01d8e8c85b8a002066e8fa31819d8.png

Guess you like

Origin blog.csdn.net/qiwoo_weekly/article/details/131798998