react-canvas README

The project's README from github.com/Flipboard/react-canvas. As one markdown file: README.md.

react-canvas

Introductory blog post

React Canvas adds the ability for React components to render to <canvas> rather than DOM.

This project is a work-in-progress. Though much of the code is in production on flipboard.com, the React canvas bindings are relatively new and the API is subject to change.

Motivation

Having a long history of building interfaces geared toward mobile devices, we found that the reason mobile web apps feel slow when compared to native apps is the DOM. CSS animations and transitions are the fastest path to smooth animations on the web, but they have several limitations. React Canvas leverages the fact that most modern mobile browsers now have hardware accelerated canvas.

While there have been other attempts to bind canvas drawing APIs to React, they are more focused on visualizations and games. Where React Canvas differs is in the focus on building application user interfaces. The fact that it renders to canvas is an implementation detail.

React Canvas brings some of the APIs web developers are familiar with and blends them with a high performance drawing engine.

Installation

React Canvas is available through npm:

npm install react-canvas

React Canvas Components

React Canvas provides a set of standard React components that abstract the underlying rendering implementation.

<Surface>

Surface is the top-level component. Think of it as a drawing canvas in which you can place other components.

<Layer>

Layer is the the base component by which other components build upon. Common styles and properties such as top, width, left, height, backgroundColor and zIndex are expressed at this level.

<Group>

Group is a container component. Because React enforces that all components return a single component in render(), Groups can be useful for parenting a set of child components. The Group is also an important component for optimizing scrolling performance, as it allows the rendering engine to cache expensive drawing operations.

<Text>

Text is a flexible component that supports multi-line truncation, something which has historically been difficult and very expensive to do in DOM.

<Image>

Image is exactly what you think it is. However, it adds the ability to hide an image until it is fully loaded and optionally fade it in on load.

<Gradient>

Gradient can be used to set the background of a group or surface.

  render() {
    ...
    return (
      <Group style={this.getStyle()}>
        <Gradient style={this.getGradientStyle()} 
                  colorStops={this.getGradientColors()} />
      </Group>
    );
  }
  getGradientColors(){
    return [
      { color: "transparent", position: 0 },
      { color: "#000", position: 1 }
    ]
  }

<ListView>

ListView is a touch scrolling container that renders a list of elements in a column. Think of it like UITableView for the web. It leverages many of the same optimizations that make table views on iOS and list views on Android fast.

Events

React Canvas components support the same event model as normal React components. However, not all event types are currently supported.

For a full list of supported events see EventTypes.

Building Components

Here is a very simple component that renders text below an image:

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({

  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='...' />
        <Text style={textStyle}>
          Here is some text below an image.
        </Text>
      </Surface>
    );
  },

  getImageHeight: function () {
    return Math.round(window.innerHeight / 2);
  },

  getImageStyle: function () {
    return {
      top: 0,
      left: 0,
      width: window.innerWidth,
      height: this.getImageHeight()
    };
  },

  getTextStyle: function () {
    return {
      top: this.getImageHeight() + 10,
      left: 0,
      width: window.innerWidth,
      height: 20,
      lineHeight: 20,
      fontSize: 12
    };
  }

});

ListView

Many mobile interfaces involve an infinitely long scrolling list of items. React Canvas provides the ListView component to do just that.

Because ListView virtualizes elements outside of the viewport, passing children to it is different than a normal React component where children are declared in render().

The numberOfItemsGetter, itemHeightGetter and itemGetter props are all required.

var ListView = ReactCanvas.ListView;

var MyScrollingListView = React.createClass({

  render: function () {
    return (
      <ListView
        numberOfItemsGetter={this.getNumberOfItems}
        itemHeightGetter={this.getItemHeight}
        itemGetter={this.renderItem} />
    );
  },

  getNumberOfItems: function () {
    // Return the total number of items in the list
  },

  getItemHeight: function () {
    // Return the height of a single item
  },

  renderItem: function (index) {
    // Render the item at the given index, usually a <Group>
  },

});

See the timeline example for a more complete example.

Currently, ListView requires that each item is of the same height. Future versions will support variable height items.

Text sizing

React Canvas provides the measureText function for computing text metrics.

The Page component in the timeline example contains an example of using measureText to achieve precise multi-line ellipsized text.

Custom fonts are not currently supported but will be added in a future version.

css-layout

There is experimental support for using css-layout to style React Canvas components. This is a more expressive way of defining styles for a component using standard CSS styles and flexbox.

Future versions may not support css-layout out of the box. The performance implications need to be investigated before baking this in as a core layout principle.

See the css-layout example.

Accessibility

This area needs further exploration. Using fallback content (the canvas DOM sub-tree) should allow screen readers such as VoiceOver to interact with the content. We've seen mixed results with the iOS devices we've tested. Additionally there is a standard for focus management that is not supported by browsers yet.

One approach that was raised by Bespin in 2009 is to keep a parallel DOM in sync with the elements rendered in canvas.

Running the examples

npm install
npm start

This will start a live reloading server on port 8080. To override the default server and live reload ports, run npm start with PORT and/or RELOAD_PORT environment variables.

A note on NODE_ENV and React: running the examples with NODE_ENV=production will noticeably improve scrolling performance. This is because React skips propType validation in production mode.

Using with webpack

The brfs transform is required in order to use the project with webpack.

npm install -g brfs
npm install --save-dev transform-loader brfs

Then add the brfs transform to your webpack config

module: {
  postLoaders: [
    { loader: "transform?brfs" }
  ]
}

Contributing

We welcome pull requests for bug fixes, new features, and improvements to React Canvas. Contributors to the main repository must accept Flipboard's Apache-style Individual Contributor License Agreement (CLA) before any changes can be merged.

react-canvas (Flipboard/react-canvas)

Searching Database…

这是什么东西?React Canvas 是 Flipboard 出品的一个开源库,让 React 组件渲染到 canvas 上而不是 DOM,用来构建更快、更像原生应用的移动网页界面。
那它在我的应用里是怎么用的——是一套组件库吗?是的:它是一个 npm 库,提供一组标准的 React 组件——Surface、Layer、Group、Text、Image、Gradient 和 ListView。你照常写 React 代码,渲染到 canvas 只是内部实现细节。
我怎么开始使用它?先从 npm 安装,把你的界面放在 Surface 里,然后用 top、left、width、height、backgroundColor 这类样式来定位 Layer 子元素。自带的示例可以用 npm start 启动,在一个支持热更新的服务器上运行,端口是 8080。
用的时候还需要别的什么吗——打包方面有什么特别注意的?它的依赖(fbjs、linebreak、scroller)npm 会自动装好。如果你用 webpack 构建,必须在 webpack 配置里加上 brfs 转换——这是唯一一个不太直观的要求。
它能用于生产环境吗?基本可以:大部分代码已经在 flipboard.com 的生产环境运行,但这个项目还在开发中,canvas 相关的绑定也比较新,所以 API 可能会有变动。
它是专门面向移动网页应用的吗?是的——Flipboard 开发它,是因为移动网页应用比起原生应用感觉很慢。它依赖现代移动浏览器里硬件加速的 canvas,ListView 还借鉴了 iOS 和 Android 的列表优化。
我能用在自己的项目里吗?有什么附加条件?代码采用宽松的 BSD-3-Clause 许可证。有一点要注意:向主仓库提交代码的人必须先签署 Flipboard 的 Apache 风格 CLA,改动才能被合并。
ListView 是怎么处理长列表滚动的?它是一个类似网页版 UITableView 的触摸滚动容器:ListView 会对视口外的条目做虚拟化,所以你要通过 numberOfItemsGetter、itemHeightGetter 和 itemGetter 这些 props 来提供数据,而不是用普通的子元素。目前所有条目的高度必须一致。
canvas 绘制的组件还能正常响应 React 事件吗?可以——这些组件支持和普通 React 组件相同的事件模型,只是并非所有事件类型都已支持,支持列表在 EventTypes 里。
能用自定义字体或者精确的多行文本吗?自定义字体目前还不支持。排版方面,measureText 可以计算文本度量信息,帮你实现精确的多行省略文本,timeline 示例就是这么做的。
屏幕阅读器能读出 canvas 渲染的界面吗?这还处于探索阶段。canvas 子树里的后备 DOM 内容应该能让 VoiceOver 这类屏幕阅读器与之交互,但在 iOS 上效果参差不齐,而且浏览器尚未支持所需的焦点管理标准。
Creator
Flipboard
Size
0.1 MB
Stars
13.2K
Updated
CommitMar 27
Age
11y
Commits · 90 Days