All files / src/components/Canvas CanvasComponent.js

17.65% Statements 3/17
0% Branches 0/6
16.67% Functions 1/6
18.75% Lines 3/16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98                                                          16x 16x                                                                                       4x                                              
/**
* Copyright 2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
 
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
 
import Canvas from '../../drawing/canvas';
import WebGL from '../../drawing/webgl';
 
import createRef from 'create-react-ref/lib/createRef';
 
/**
 * Constructs a drawable canvas (e.g. HTML Canvas or WebGL) and provides it as
 * a reference.
 *
 * On every redraw, this.draw() gets called.
 */
class CanvasComponent extends PureComponent {
 
  static defaultProps = {
    engine: "canvas",
  }
 
  constructor(props) {
    super(props);
    this.canvas = createRef();
  }
 
  componentDidMount() {
    // choose the best engine
    if (this.props.engine === "webgl" && WebGL.isSupported(this.canvas.current)) {
      this.ctx = new WebGL(this.canvas.current);
    } else {
      this.ctx = new Canvas(this.canvas.current);
    }
    this.draw();
  }
 
  componentDidUpdate() {
    this._draw();
  }
 
  _draw() {
    if (!this.ctx) return;
    this.ctx.startDrawingFrame();
    this.ctx.save();
    this.draw();
    this.ctx.restore();
    this.ctx.endDrawingFrame();
  }
 
  draw() {
    console.error("Implement me.");
  }
 
  render() {
    return (
      <div style={this.props.style}>
        <canvas
          ref={this.canvas}
          width={this.props.width}
          height={this.props.height}
        >
        </canvas>
      </div>
    );
  }
}
 
CanvasComponent.propTypes = {
  /**
   * Width of the component (in pixels), e.g. `100`
   */
  width: PropTypes.number.isRequired,
 
  /**
   * Width of the component (in pixels), e.g. `100`
   */
  height: PropTypes.number.isRequired,
 
  /**
   * Custom style configuration.
   */
  style: PropTypes.object,
 
  /**
   * Rendering engine: `canvas` or `webgl` (experimental).
   */
  engine: PropTypes.oneOf(['canvas', 'webgl']),
}
 
export default CanvasComponent;