Skip to content

Instantly share code, notes, and snippets.

@azz
Last active April 15, 2023 14:28
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save azz/1842c13a5c5fd32f9e07 to your computer and use it in GitHub Desktop.
Save azz/1842c13a5c5fd32f9e07 to your computer and use it in GitHub Desktop.
Two.js and React with ES6
"use strict";
import React from "react";
import Two from "two";
class TwoTest extends React.Component {
constructor (props) {
super(props);
this.state = {
y1: window.innerHeight / 2,
y2: window.innerHeight / 2,
y3: window.innerHeight / 2,
right: 0,
bottom: 0,
};
this.line = null;
this.two = null;
this.resize = this.resize.bind(this);
this.updateShape = this.updateShape.bind(this);
}
componentWillMount() {
var two = new Two({
type: Two.Types[this.props.type],
fullscreen: true
});
this.two = two;
}
componentDidMount() {
var two = this.two;
two.bind('resize', this.resize)
.appendTo(this.refs.stage.getDOMNode())
.trigger('resize')
.update();
this.setState({
y1: two.height / 2,
y2: two.height / 2,
y3: two.height / 2
})
this.line = this.two.makeCurve(
two.width / 5, this.state.y1,
two.width / 2, this.state.y2,
4 * two.width / 5, this.state.y3,
true
);
this.line.linewidth = 4;
this.line.cap = 'round';
}
componentWillUnmount() {
this.state.two.unbind('resize', this.resize);
}
componentWillUpdate(nextProps, nextState) {
for (var i = 0; i < 3; i++) {
var y = 'y' + (i+1);
if (this.state[y] !== nextState[y]) {
this.line.vertices[i].y = window.innerHeight / 2 - this.state[y];
}
}
}
componentDidUpdate(prevProps, prevState) {
this.two.update();
}
resize() {
this.setState({
right: this.two.width,
bottom: this.two.height
});
}
updateShape({ target }) {
this.setState({ [target.name]: target.value });
}
render() {
return (
<div>
<div ref="stage" style={{height: 100 + '%'}}></div>
<ul id="controls">
<li>
<ul className="select">
<li className="title centered">
<span>y1</span>:
<input type="range" name="y1" onChange={this.updateShape}
min={0} default={this.state.y1} max={this.state.bottom}></input> ({this.state.y1})
</li>
</ul>
</li>
<li>
<ul className="select">
<li className="title centered">
<span>y2</span>:
<input type="range" name="y2" onChange={this.updateShape}
min={0} default={this.state.y2} max={this.state.bottom}></input> ({this.state.y2})
</li>
</ul>
</li>
<li>
<ul className="select">
<li className="title centered">
<span>y2</span>:
<input type="range" name="y3" onChange={this.updateShape}
min={0} default={this.state.y3} max={this.state.bottom}></input> ({this.state.y3})
</li>
</ul>
</li>
</ul>
</div>
);
}
}
window._dottedNested = function (key, value) {
return key.split('.').concat(value).reduceRight((acc, val) => { return { [val]: acc }});
}
React.render(<TwoTest type="svg" />,
document.getElementById('react-main'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment