Paper.js

by duckywang1

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Paper.js Demo</title>
  <script src="https://cdn.bootcss.com/react/16.2.0/umd/react.development.js"></script>
  <script src="https://cdn.bootcss.com/react-dom/16.2.0/umd/react-dom.development.js"></script>
  <script src="https://cdn.bootcss.com/paper.js/0.22/paper.js"></script>
</head>
<body>
  <div id="reactPage"></div>
</body>
</html>

Babel + JSX

class CuttleCanvas extends React.Component {
  paperInstance;

	constructor(props) {
  	super(props);
    const ctx = this;
    [
      'canvasRef',
      'changeColor',
    ].forEach((funcName) => {
    	ctx[funcName] = ctx[funcName].bind(ctx);
    });
  }

  canvasRef($el) {
    const paperInstance = new paper.PaperScope();
    this.paperInstance = paperInstance;
  	paperInstance.setup($el);
    
    var path = new paper.Path();
    path.strokeColor = this.props.strokeColor;
    var start = new paper.Point(100, 100);
    path.moveTo(start);
    path.lineTo(start.add([ 200, -50 ]));
    paperInstance.view.draw();
  }
  
  changeColor() {
    console.log(paper);
  	if (this.props.isCurrent) {
      this.paperInstance.project.activeLayer.lastChild.strokeColor = 'yellow';
      this.paperInstance.project.activeLayer.lastChild.selected = true;
      this.paperInstance.view.draw();
    }
  }

  render() {
  	return (
    	<div className="Hello">
      	<p>Hello Cuttle</p>
        <button onClick={this.changeColor}>变色</button>
        <canvas ref={this.canvasRef} resize={true} />
      </div>
    );
  }
}

class ReactPage extends React.Component {
  render() {
    return (
    	<div>
      	<CuttleCanvas isCurrent={true} strokeColor="black" />
        <CuttleCanvas isCurrent={false} strokeColor="red" />
      </div>
    );
  }
}

// paper.install(window);

ReactDOM.render(
  <ReactPage />,
  document.getElementById('reactPage')
);

console.log(paper);