Data visualization

You can download github/data-view related code to help understand.

1, canvas,

1.1. Why learn Canvas?

Canvas can draw complex graphics, process images, animate, develop games, process videos…

For example: we usually use div+ CSS can only do some simple graphics, such as: square, rectangle, circle, ellipse…… However, canvas can be used to make triangles, polygons and petals……

1.2. What is Canvas?


is defined in MDN like this:

< Canvas > is a new element in HTML5 that can be used to draw graphics using scripts in JavaScript. For example, it can be used to draw graphics, make photos, create animations, and even do real-time video processing or rendering.

The important point here is that

is just a canvas and does not have the ability to draw itself. Drawing must use scripting languages such as JavaScript.

The

tag allows scripting languages to render bitwise images dynamically. The

tag creates a drawable area that JavaScript code can access through a full set of drawing functions similar to other general-purpose TWO-DIMENSIONAL apis to generate dynamic graphics.

We can think of the

tag as just a rectangular canvas. JavaScript is the paintbrush, and is responsible for drawing on the canvas.

In a broad sense: the new Canvas 2D drawing function of H5

In HTML: Canvas is an HTML tag (with tag attributes); Canvas can be understood as a canvas; Use JS to draw graphics in canvas.

1.3. Set canvas size

Set the width and height properties of the Canvas DOM element

⚠️ Note: Do not use CSS to set the canvas size

#canvas{
  background-color: aliceblue;
}
Copy the code
<canvas id="canvas" width="300" height="500"></canvas>  
Copy the code
/ / the canvas
const canvas= document.getElementById("canvas");
canvas.width = 200;
canvas.height = 100;
Copy the code

The code above shows you a canvas and sets its size.

1.4. Canvas Context Object

Method to get a context object: Canvas.getContext (‘2d’)

 / / brush
const ctx = canvas.getContext('2d')
ctx.fillRect(100.200.300.400) // x,y,w,h
Copy the code

1.5. Drawing form of graphics

1.5.1, rectangle

Rectangle drawing method:

  • FillRect (x,y,w,h)
  • Stroke rectangle method: stokeRect(x,y, W,h)
  • ClearRect (x,y,w,h)
// Fill the rectangle
ctx.fillRect(100.100.100.100) // x,y,w,h
/ / color
ctx.strokeStyle = 'red'
/ / line width
ctx.lineWidth = 5
// Stroke rectangle
ctx.strokeRect(100.100.100.100)
// Clear the rectangle
ctx.clearRect(100.100.100.100)
// Clean up the canvas
ctx.clearRect(0.0,canvas.width,canvas.height)
Copy the code

1.5.2, path

Drawing path steps:

BeginPath () 2. Add subpaths to the path set. Display path: fill fill(); Stroke stroke ()

Shape of sub-path:

  • Line: lineTo (x, y); lineTo(x,y); lineTo(x,y)
  • Arc: Arc (x,y, radius, start radian, end radian, direction)
  • Tangent arc: arcTo(x1,y1,x2,y2, radius)
  • Quadratic bezier curves: quadraticCurveTo(x1, y1, x, y); (Draw a conic curve from the previous point up to (x, y) with (x1, y1) as the control point.)
  • 3. BezierCurveTo (x1, y1, x2, y2, x, y) (draw a curve from the previous point up to (x, y) with (x1, y1) and (x2, y2) as control points)

* Rect (x,y,w.h)

1.5.3 Coloring area of the graph

There are two types of colored areas for graphics:

1, Stroke area: strokeStyle 2, fill area: fillStyle

1.5.4 Text rendering

There are two ways to draw text:

1, strokeText(text,x,y,maxWidth) 2, fillText(text,x,y,maxWidth)

MeasureText: measureText(Text)

Set font: ctx.font = ‘bold 20px serif’ // Thickness, size, font

// start left end right center

Textbaseline // Top middle bottom hanging ideographic

1.5.5 State Management

State management, which manages the state of context objects.

The state of the context object is the property of the context object. For example: second color, fill color, drop shadow, line style…

There are two ways to manage context state:

  • Save current state: save()
  • Restore the last saved state: restore()

When graphics with the same style are drawn, they are wrapped by save() and restore() to prevent the current graphics style from affecting later graphics styles.

1.5.6. Graphic Selection

Canvas graphics have no methods to listen for events.

For example, when selecting a graph with the mouse, only the canvas canvas can be used to monitor the event, obtain the position of the mouse or touch point in the canvas, and then judge whether the mouse point in the canvas is in the graph based on the position and shape of the graph and the canvas.

Prerequisite for sector selection:

  • Center position: Center
  • Radius: the radius
  • Start radian: startAngle
  • Endarc: endarc l

1.6, the pie chart

Pie charts are mainly used to show the proportion of different data in the total number.

The arc length of the sector indicates the proportion of the class, that is, the pie chart is composed of multiple sectors.

The core of the pie chart:

  • The fan
  • Guide line + label text
  • Prompt box
  • Mouse over events

It is known that: * With the center of the circle pos as the starting point, make a ray to divide the sector evenly, and point P1 on this ray. * the distance from p1 to the center of the circle is 20 longer than the radius to find: p1 position x, y theorem: according to the direction and length of the vector, can find the point solution: Direction = (end radian – initial radian)/2+ Initial radian Length = Radius +20 x = math.cos (direction)* length + pos.x y = Math.sin(direction)* Length + pos.y

Ha ha, do you remember the trig formula? !

1.6.1 Dynamic effect of pie chart

Pie chart animation:

  • Elastic animation
  • Slow to follow

Business logic for animation:

1, initial state 0: fan from small to large, elastic movement 2, mouse into 1: fan expanded a little, elastic movement; Hint slow follow 3, mouse out 2: fan narrowed a little, elastic movement; Prompt hidden

1.6.2 Pie chart dichotomy

A dichotomy is a dichotomy.

1.6.3 Complete pie chart version

Pie chart drawing steps:

1. Declare required data 2. Construct data 3

1.7 summary of Canvas

In fact, the wonderful part of Canvas lies in the combination of program algorithm and art. That is, it can use logical algorithms to show the laws of art and beauty.

If you like or are interested in canvas, It’s Amazing! Application scenarios: drawing charts (ECharts), small games (H5 games), active pages (turntables, scratch-off), small special effects, cool background…..

2, echarts

Echarts is an open source visualization library based on JavaScript

There are also quick Start tutorials on the website to help us use Echarts.

2.1 common Components of Echarts

Echarts common components:

  • Title the title
  • Legend legend
  • The toolbox toolbar
  • Prompt box tooltip
  • Axis xAxis yAxis
  • List of series

2.2 echarts Common charts

Echarts commonly used charts:

  • The line chart line
  • Histogram bar
  • Pie pie
  • Scatterplot scatter
  • K line graph candlestick
  • Radar radar
  • The gauge on the dashboard

2.3. Echarts Dataset

The DATASET dataset component is available from Echarts4 for data management.

Advantages of dataset:

  • Based on the raw data, set the mapping relationship and form the chart
  • Data and configuration are separated for independent management
  • Data can be reused by multiple families or components
  • Support more common formats for data, such as two-dimensional arrays, object arrays, etc

2.3.1 Mapping method of data set and chart

  • Column 1 maps the category axis
  • Column 2, series 1
  • Column 3, series 2
  • .
// Specify the chart configuration items and data
const option = {
  legend: {},
  tooltip: {},
  dataset: {
    // Provide a piece of data.
    source: [['product'.'2015'.'2016'.'2017'],
      ['Latte'.43.3.85.8.93.7],
      ['Tea'.83.1.73.4.55.1],
      ['Cocoa'.86.4.65.2.82.5],
      ['Brownie'.72.4.53.9.39.1]]},// X-axis, category axis (category). By default, the category axis corresponds to the first column of the dataset.
  xAxis: {type: 'category'},
  // Y axis, numeric axis.
  yAxis: {},
  // Multiple bar series. By default, each series automatically corresponds to each column of the dataset.
  series: [{type: 'bar'},
    {type: 'bar'},
    {type: 'bar'}};Copy the code

Or you can use the usual array of objects format:

// Specify the chart configuration items and data
const option = {
  legend: {},
  tooltip: {},
  dataset: {
    // The order of dimension names is specified so that the default dimension to axis mapping can be used.
    // If dimensions is not specified, the mapping can be done by specifying series.encode
    dimensions: ['product'.'2015'.'2016'.'2017'].source: [{product: 'Latte'.'2015': 43.3.'2016': 85.8.'2017': 93.7},
      {product: 'Tea'.'2015': 83.1.'2016': 73.4.'2017': 55.1},
      {product: 'Cocoa'.'2015': 86.4.'2016': 65.2.'2017': 82.5},
      {product: 'Brownie'.'2015': 72.4.'2016': 53.9.'2017': 39.1}},xAxis: {type: 'category'},
  yAxis: {},
  series: [{type: 'bar'},
    {type: 'bar'},
    {type: 'bar'}};Copy the code

2.3.2 Row and column mapping of data sets

Based on column mapping:

serieslayoutBy: colum, 

// The X-axis is Latte, Tea, Cocoa, Brownie
dataset: {
  source: [['product'.'2015'.'2016'.'2017'],
    ['Latte'.43.3.85.8.93.7],
    ['Tea'.83.1.73.4.55.1],
    ['Cocoa'.86.4.65.2.82.5],
    ['Brownie'.72.4.53.9.39.1]]},Copy the code

Based on row mapping:

serieslayoutBy: row, 

// The X-axis is '2015', '2016', '2017'.
dataset: {
  source: [['product'.'2015'.'2016'.'2017'],
    ['Latte'.43.3.85.8.93.7],
    ['Tea'.83.1.73.4.55.1],
    ['Cocoa'.86.4.65.2.82.5],
    ['Brownie'.72.4.53.9.39.1]]},Copy the code

2.4. Style Settings in Echarts

Echarts styles can be set in the following ways:

  • Color theme
  • Color palette
  • Specific style Settings (itemStyle, lineStyle, areaStyle, label…)
  • visualMap

2.4.1 Color Theme

The color theme is a way to modify global styles.

Echarts has two built-in themes, light and Dark, set as follows:

echarts.init(dom, 'light’)
Copy the code

To use other themes, go to theme downloads.

3, large screen

In popular terms, the big screen is the webpage displayed on the big screen. It is also common for us to do data visualization.

Large screens are usually placed in public Spaces or in prominent places to display data.

Large screens are typically designed to be 1920 by 1080, regardless of browser compatibility, as long as Google Chrome is compatible.

Large screens are created by creating multiple Echarts containers within a page and placing different Echarts diagrams into them.

3.1 Adaptive of large screen

There are two aspects to consider when adapting to a large screen:

1. Screen size adaptation of Echarts containers.

  • CSS basics such as Flex layout, percentage positioning…

2. Adaptation of echarts chart to container size.

  • Percentage positioning of chart elements, such as left: ‘20%’
  • Use Echarts’ media capabilities for responsive layout.

Note: The resize() method of echarts instances can change the diagram size when the container size changes.

3.2 common layout of Large screens