[black technology] React-canvas helps HTML5

  javascript

图片描述

1. What is smooth user experience?

The game development community has a theory that when the animation or interactive response reaches 60FPS(60 frames per second), it can be defined as smooth. According to this theory, all operations in each frame must be completed in 16ms. In order to improve the user experience of the page, efforts must be made on performance. The earliest animation was realized by setTimeout, and the time precision of setTimeout in callback processing was about 16ms. Therefore, it can be imagined that the normal use of the two functions of the page has been 16 ms, plus Reflow/Repaint/Composition Carton or frame skipping is a common occurrence. Fortunately, however, w3c standards and browser vendors have earlier supported the animation interface RAF(RequestAnimationFrame function) to handle animation frame callbacks. The problem of insufficient setTimeout is solved. However, another problem is still unsolved. When the browser opens the web page, it needs to parse the document and generate DOM structure in memory. If it encounters complicated documents, this process is very slow. If you encounter a low-end mobile browser, imagine how long it will take to generate DOM if there are tens of thousands of shapes (whether pictures or CSS) on the web page. Not to mention interacting with one of the shapes.

What is React?

The interaction between the user and the browser is technically that the user is operating the DOM. All DOM operations are synchronized and will block the browser. When JavaScript operates DOM, it must wait until the previous operation is finished before the latter operation can be executed. As long as one operation has Caton, the whole web page will lose its response for a short time. The frequency of browser redrawing web pages is 60FPS, JavaScript cannot complete DOM operations in 16 milliseconds, thus generating frame skipping. This is the source of the unsmooth and incoherent user experience. JavaScript language itself is very efficient, but DOM is too slow, DOM slows JavaScript down. In order to solve this problem, React appeared. React is an open source framework of JavaScript introduced by Facebook to build a user interface. The most striking feature of React is the introduction of the concept DOM(Virtual DOM, which implements a set of DOM API with JavaScript on the browser side. When developing based on React, all DOM structures are constructed through virtual DOM. Whenever the user interface needs to change, React reconstructs the entire DOM tree. Then React compares the current entire DOM tree with the previous DOM tree to obtain the difference of DOM structures, and then updates the actual browser DOM only for the parts that need to change. React implements the method of minimizing code participation in DOM operations, greatly improving browser performance.

What is Canvas?

Canvas is a canvas element of HTML5 and also a native DOM element. It is equivalent to a “white board”, on which we can add text and images through javascript and “draw” some visual content. At present, most H5 games and animation effects are implemented by canvas. Many small games and applications spread in WeChat are also implemented by canvas. With canvas, the entire page uses only one DOM element, and the browser only needs to draw one picture at a time. This greatly reduces the amount of DOM and rendering complexity. Even better, canvas supports GPU hardware acceleration by default and can change the original CPU intensive operation into GPU operation. The smoothness of animation is improved. It is worth mentioning that the kernel of WeChat browser, namely QQ Browser X5 kernel, has built many game engines (such as Egret Game Engine and cocos2dx) for developers to develop canvas games, so in the long run, WeChat browser’s canvas performance will become more and more powerful.

4. New Methods

Most modern mobile devices have a hardware accelerated canvas, why don’t we use it? The HTML5 game has already been done. Why don’t we use the idea of game to design the interface, develop the application interface on canvas, and render the page with canvas? I believe you have already thought of it, but someone has already done it, that is, Flipboard’s React-canvas. What is React-canvas? Just look at the name and you will know that this is related to react and canvas. React-canvas can enable us to render canvas with reach technology.

5. introduction to React-canvas

React Canvas is a component that depends on React. It has the ability to render to canvas. It can let us get rid of the tedious canvas imperative drawing and use simple css Layout. Next, I will show you a simple graphic implementation.

5.1. install node

The front-end development of the new era cannot be separated from the node environment, so react-canvas is no exception, and the detailed steps of node installation will not be repeated here. Remember, Node version is not less than 4.0.

图片描述

5.2 Create Project Space

Create a folder in D:nodejsreactdemo, which is the root directory for development.
Open to this directory, switch to the command line, execute npm init, default carriage return, initialize package.json

5.3 Installing Frames and Plug-ins

A series of frameworks need to be installed on the node environment.
Switch to the command line.
carry out

npm install react

Install the base frame reactv0.13.0I didn’t test the new edition, I don’t know if it is feasible).
carry out

npm install jsx-loader

To install and compile reactjsx-loaderPlug-ins,
carry out

npm install react-canvas

Installing the Core Frameworkreact-canvas,
carry out

npm install webpack

Webpack, a tool for installing packaged code.
Then create a text fileindex.html,
Create profilewebpack.config.js,
Create js folder to store code files.
At this point, your working environment should have

图片描述

among themnode_modulesFolder, there should be at least automatically generatedreact、react-canvas、webpackThree folders.

5.4 Let Code Run

Openindex.htmlFile, code is as follows:

<!  DOCTYPE html>
 <html>
 <head>
 <meta http-equiv="Content-type" content="text/html;  charset=utf-8">
 <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
 < title>react canvas first step < /title >
 </head>
 <body>
 <div id="main"></div>
 <script src="bundle.js"></script>
 </body>
 </html>

There is only one main pageid=mainThedivLabel and chain one outsidejsDocuments.
OpenjsFolders, creatingindex.js, code is as follows

var React = require('react');
var ReactCanvas = require('react-canvas');

var Surface = ReactCanvas.Surface;
var Image = ReactCanvas.Image;
var Text = ReactCanvas.Text;

var MyComponent = React.createClass({

//interface rendering
render: function () {
var surfaceWidth = window.innerWidth;
var surfaceHeight = window.innerHeight;
var imageStyle = this.getImageStyle();
var textStyle = this.getTextStyle();

return (
<Surface width={surfaceWidth} height={surfaceHeight} left={0} top={0}>
<Image style={imageStyle} src='http://img1.gtimg.com/joke/pics/hv1/193/44/1996/129801313.png' />
<Text style={textStyle}>
Ha ha, you hit me
</Text>
</Surface>
);
},
//Calculate Center
getImageHeight: function () {
return Math.round(window.innerHeight / 2);
},
getImageWidth: function () {
return Math.round(window.innerWidth / 2);
},

//picture style
getImageStyle: function () {
return {
top: this.getImageHeight() -32,
left: this.getImageWidth() -32,
width: 64,
height: 64
};
},

//Text style
getTextStyle: function () {
return {
top: this.getImageHeight() + 64,
left: 0,
width: window.innerWidth,
height: 20,
lineHeight: 20,
fontSize: 12,
textAlign : 'center'
};
}

});
React.render(<MyComponent />, document.getElementById('main'));

Configurationwebpack.config.js

module.exports = {
//Entry File
entry: './js/main.jsx',
//Output File
output: {
path: __dirname,
filename: 'bundle.js'
},
module: {
loaders: [
//Anyone who meets the end of jsx or js will be loaded with jsx-loader.
//and harmony mode is enabled
{ test: /\.jsx$/, loader: 'jsx-loader?  harmony'},
{ test: /\.js$/, loader: 'jsx-loader?  harmony'},
]
},
//Indicates that this dependency is an external lib. It does not need to be compiled when it meets require.
//and correspond to window.React on the browser side
//externals: {
//'react': 'window.React'
//},
//now you can write require('file') instead of require('file.jsx')
resolve: {
root: __dirname,
extensions: ['', '.js', '.jsx']
}
};

After the configuration is completed, switch to the command line for execution.
webpack -p
Command, Package, Compile
After packaging, generate one in the root directorybundle.js, directly open with a browser, you can see the effect.

图片描述

Online demo address:Point me

6. Syntax and Elements (Labels, Components)

react-canvasThe grammar andreactSimilarly, if you are familiar with react, react-canvas is easy to use. React-canvas has customized several labels. These labels are also standardReact components.

<Surface>

Surface is a top-level label and a container. You can put any element on it. You can think of it as a canvas element. The whole project should be nested inside a surface. Already used in the above example.

<Layer>

The Layer level is second only to surface and other elements can be placed. Basic styles and attributes such astop, width, left, height, backgroundColor and zIndexCan be set at this level.

<Group>

Group is a container, because when react renders a component, there must be a total tag containing all hash tags. In react-canvas, Group plays the role of div and can be used as the parent tag of scattered tags. Encapsulating a series of associated tags with Group can improve the cohesion and modularity of code on the one hand, and improve the performance of page scrolling on the other.

<Text>

Text is used to store Text and is a flexible label. canvas does not support automatic line break, while Text label does.

<Image>

Image, as you imagine, is used to put pictures. However, it supports displaying only after loading and can be hidden at will.

<ListView>

ListView is a list, which can be considered as equivalent to that in HTML pages.ulOr ..native apphit the targetUITableView, which can improve page scrolling performance.
At the same time, react-canvas gives event support to each label, includingtouchstart,move,end,clickSuch as events.

7. Scroll list of pictures and texts

Next, I’ll introduce how to create a system that achieves60 fps, a paginated scrolling list. Facts have proved that this is very easy to implement.
Modifymain.jsThe code is

/** @jsx React.DOM */
 
 'use strict';
 
 var React = require('react');
 var ReactCanvas = require('react-canvas');
 // page file is responsible for rendering a single page
 var Page = require('./components/Page');
 // data file stores json format graphics and text
 var articles = require('./common/data');
 
 var Surface = ReactCanvas.Surface;
 var ListView = ReactCanvas.ListView;
 
 var App = React.createClass({
 //Render the entire list
 render: function () {
 var size = this.getSize();
 return (
 <Surface top={0} left={0} width={size.width} height={size.height}>
 <ListView
 style={this.getListViewStyle()}
 snapping={true}
 scrollingDeceleration={0.92}
 scrollingPenetrationAcceleration={0.13}
 numberOfItemsGetter={this.getNumberOfPages}
 itemHeightGetter={this.getPageHeight}
 itemGetter={this.renderPage} />
 </Surface>
 );
 },
 //Render Single Page
 renderPage: function (pageIndex, scrollTop) {
 var size = this.getSize();
 var article = articles[pageIndex % articles.length];
 var pageScrollTop = pageIndex * this.getPageHeight() - scrollTop;
 return (
 <Page
 width={size.width}
 height={size.height}
 article={article}
 pageIndex={pageIndex}
 scrollTop={pageScrollTop} />
 );
 },
 //browser size
 getSize: function () {
 return document.getElementById('main').getBoundingClientRect();
 },
 //Appearance of the entire list
 getListViewStyle: function () {
 var size = this.getSize();
 return {
 top: 0,
 left: 0,
 width: size.width,
 height: size.height,
 };
 },
 //Set the number of scrollable pages. If the number exceeds the number of pages, scroll circularly
 getNumberOfPages: function () {
 return 9;
 },
 //Calculate the height of a single page
 getPageHeight: function () {
 return this.getSize().height;
 }
 
 });
 
 React.render(<App />, document.getElementById('main'));

The whole page code consists of a surface, a listview and 9 pages, which can be scrolled up and down. React-canvas turns the webpage into a canvas, and the user is interacting with the picture, thus bypassing DOM and reducing the operation delay. Moreover, canvas can be accelerated by hardware, which improves performance and makes the experience very smooth.

You can check this onlineDemo, order mePc users remember to use chrome to simulate a mobile browser. The complete source code for the implementation is attached at the end of the article.

8. advantages and disadvantages of React-canvas

8.1 advantages

React-canvas uses a canvas element to draw the interface and complete scrolling. At each touch event, the rendering tree is updated according to the current scrolling degree. After that, the entire rendering tree is re-rendered with the new coordinates. There is an important technology canvas(off-screen canvas on canvas, which can be drawn in memory now, then copied to the user interface at one time, and redrawn using off-screen layer is also very fast. React will do diff of the virtual DOM before updating the interface. Only changed interfaces are updated in the render () function, and React further improves the performance of React-canvas. Fluency is the main advantage of React-canvas.
The code is based on react, because react is popular now, many front-ends are already familiar with the writing of react, and react also has many related components, so react-canvas is suitable for some people to get started quickly. In addition, the compatibility is relatively good, inheriting the compatibility and cross-platform advantages of react and canvas.

8.2 Disadvantages

At present, it is immature and unstable, and react is changing all the time, so React-canvas will be upgraded along with it. React-canvas is not perfect, and many tag features in DOM are not implemented in react-canvas at present, for example, the text cannot be copied, which makes the use of React-canvas somewhat limited. This project has already been opened up on Github, and the author is also reconstructing the project, hoping that it will be a powerful version when it is updated next time. In addition, the learning cost of react-canvas is relatively high, and the use of react-canvas requires a certain understanding of react and canvas.

9. Summary

React Canvas cannot completely replace DOM. Personally, I think it is only applicable to mobile web (or webview). The hardware resources of the mobile phone are relatively limited and the user interaction is relatively frequent. We can use it in the places where the performance requirements are most critical in our pages, especially in the scrolling view which is very common in WeChat browsers. DOM may be a better method when rendering performance is not a problem. In fact, DOM is the only method for certain elements such as input fields, audio/video tags, etc. In a sense, react-canvas is also a hybird application. Compared with traditional native applications, react-canvas content is all web. We can implement the interface based on dom in the development, and use canvas rendering in appropriate places. DOM and canvas have their own advantages and complement each other. React-canvas can improve the interaction and performance level of the page to compete with local applications, which is what attracts attention.


10. Amway Time

In the process of web development, we have all seen or used some strange techniques and tricks. this technique is collectively referred to as black magic. these black magic are scattered in all corners. in order to make it convenient for everyone to consult and learn, we have collected, sorted out and classified them, and made a project on github-awesome-blackmargic, I hope you love to study the developers can like, also hope you can share their unique skills, if you are interested can send us pr.

If you are interested in React and want to know more about React, join our QQ group (784383520).