plot

by evgkch

HTML

<div id="app"></div>

CSS

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

svg {
  border: solid 1px black;
}

React

const f = t => x => - x * t - Math.pow(t, 2);

const createLine = t=>{
	const _f = f(t);
	return {
  	x1: 0 + 150,
    y1: _f(0) + 150,
    x2: 300,
    y2: _f(300),
  };
};

function range(from, to, n = 1){
	const buffer = [];
  const m = (from - to) / n;
  for (let i = 1; i <= m; i++)
  	buffer.push((from - to) / i);
  return buffer;
}

class TodoApp extends React.Component {
  constructor(props) {
    super(props);
    this.node = null;
    this.state = {
    	x: null,
      y: null
    };
  }
  componentDidMount(){
  	this.node.addEventListener('mousemove', this.onMouseMove);
  }
  componentWillUnmount(){
  	this.node.removeEventListener('mousemove', this.onMouseMove);
  }
  onMouseMove = evt=>{
  	const nodeRect = this.node.getBoundingClientRect();
    console.log(nodeRect);
    const origin = {
    	x: (nodeRect.right + nodeRect.left) / 2,
    	y: (nodeRect.bottom + nodeRect.top) / 2,
    };
  	const x = evt.clientX - origin.x;
    const y = - evt.clientY + origin.y;
    this.setState({ x: Math.floor(x), y: Math.floor(y) });
  }
  setNode = target=>{
  	this.node = target;
  }
  renderLine = t=>{
  	const params = createLine(t);
  	return <line key={t.toString()} {...params} stroke="black" />
  }
  render() {
    return (
      <div>
      <div>{this.state.x},{this.state.y}</div>
      <svg ref={this.setNode} width="300px" height="300px" > 
        {range(-1,1, 100).map(this.renderLine)}
      </svg>
      </div>
    )
  }
}

ReactDOM.render(<TodoApp />, document.querySelector("#app"))