Skip to content

Instantly share code, notes, and snippets.

@implicit-invocation
Created August 23, 2018 13:20
Show Gist options
  • Save implicit-invocation/2d98dd7736a8758f8731693b6b6e008b to your computer and use it in GitHub Desktop.
Save implicit-invocation/2d98dd7736a8758f8731693b6b6e008b to your computer and use it in GitHub Desktop.
import React, { Component } from 'react';
import './App.css';
class App extends Component {
state = {
op1: [100, 100],
op2: [200, 100],
op3: [200, 200],
op4: [100, 200],
p1: [100, 100],
p2: [200, 100],
p3: [200, 200],
p4: [100, 200],
origin: [0, 0],
rotation: 0
};
rotate(rotation) {
rotation = parseFloat(rotation);
this.setState({
rotation
});
this.updatePoints();
}
updatePoints() {
let { op1, op2, op3, op4, origin, rotation } = this.state;
let rotationInRad = rotation * (Math.PI / 180);
const sin = Math.sin(rotationInRad);
const cos = Math.cos(rotationInRad);
const [oX, oY] = origin;
let [p1, p2, p3, p4] = [op1, op2, op3, op4].map(p => {
let [x, y] = p;
let newX = cos * (x - oX) - sin * (y - oY) + oX;
let newY = sin * (x - oX) + cos * (y - oY) + oY;
return [newX, newY];
});
this.setState({
p1,
p2,
p3,
p4
});
}
changeOrigin(axis, value) {
value = parseFloat(value);
const { origin } = this.state;
origin[axis] = value;
this.setState({ origin });
this.updatePoints();
}
render() {
const { p1, p2, p3, p4, origin, rotation } = this.state;
return (
<div className="App">
<div>
<svg width="300" height="300">
{[p1, p2, p3, p4].map((p, i) => (
<circle key={i} cx={p[0]} cy={p[1]} r="5" fill="red" />
))}
<circle cx={origin[0]} cy={origin[1]} r="5" fill="black" />
</svg>
</div>
<div>
Rotation (
{rotation}
{' '}
degree):
{' '}
<input
type="range"
value={rotation}
min="0"
max="360"
step="1"
onChange={e => this.rotate(e.target.value)}
/>
</div>
<input
type="range"
value={origin[0]}
min="0"
max="300"
step="1"
onChange={e => this.changeOrigin(0, e.target.value)}
/>
<input
type="range"
value={origin[1]}
min="0"
max="300"
step="1"
onChange={e => this.changeOrigin(1, e.target.value)}
/>
</div>
);
}
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment