Skip to content

Instantly share code, notes, and snippets.

@tengla
Created November 13, 2018 22:10
Show Gist options
  • Save tengla/5a13e942663da2c3369765511e85adfb to your computer and use it in GitHub Desktop.
Save tengla/5a13e942663da2c3369765511e85adfb to your computer and use it in GitHub Desktop.
An analog clock in React.
import React, { Component } from 'react';
const style = {
container: {
position: 'relative',
height: '420px',
width: '420px',
margin: '0 auto',
border: '1px solid #aaa'
},
digi: {
width: '420px',
margin: '0 auto',
textAlign: 'center'
},
seconds: {
position: 'absolute',
border: '1px solid #ccc',
width: '20px',
height: '20px',
backgroundColor: 'beige',
textAlign: 'center',
borderRadius: '50%',
fontSize: '16px'
}
};
const DIAMETER = 400;
const RADIUS = DIAMETER / 2;
const secondsNow = _ => new Date().getSeconds();
const minutesNow = _ => new Date().getMinutes();
const hourNow = _ => {
const h = new Date().getHours();
return h > 12 ? (h - 12) : h;
};
const X = (cx, radius, angle) => cx + (radius * Math.cos((angle + (-90)) * (Math.PI / 180)));
const Y = (cy, radius, angle) => cy + (radius * Math.sin((angle + (-90)) * (Math.PI / 180)));
export default class Clock extends Component {
state = { x: 0, y: 0, xx: 0, yy: 0, xxx: 0, yyy: 0 };
componentDidMount() {
setInterval(() => {
const secondAngle = 6 * secondsNow();
const minutesAngle = 6 * minutesNow();
const hourAngle = 0.5 * (60 * hourNow() + minutesNow());
const x = Math.floor(X(RADIUS, RADIUS, secondAngle));
const y = Math.floor(Y(RADIUS, RADIUS, secondAngle));
const xx = Math.floor(X(RADIUS, RADIUS - 50, minutesAngle));
const yy = Math.floor(Y(RADIUS, RADIUS - 50, minutesAngle));
const xxx = Math.floor(X(RADIUS, RADIUS, hourAngle));
const yyy = Math.floor(Y(RADIUS, RADIUS, hourAngle));
this.setState({ x, y, xx, yy, xxx, yyy });
}, 1000);
}
render() {
const { x, y, xx, yy, xxx, yyy } = this.state;
const sec = Object.assign({}, style.seconds, {
top: y + 'px',
left: x + 'px',
});
const min = Object.assign({}, style.seconds, {
top: yy + 'px',
left: xx + 'px',
backgroundColor: 'offwhite'
});
const hour = Object.assign({}, style.seconds, {
top: yyy + 'px',
left: xxx + 'px',
backgroundColor: 'offwhite'
});
return (
<>
<div style={style.container}>
<div style={hour}>{hourNow()}</div>
<div style={sec}>{secondsNow()}</div>
<div style={min}>{minutesNow()}</div>
</div>
<div style={style.digi}>
{new Date().getHours()}:{new Date().getMinutes()}:{new Date().getSeconds()}
</div>
</>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment