-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathSineWave.js
More file actions
57 lines (49 loc) · 1.47 KB
/
Copy pathSineWave.js
File metadata and controls
57 lines (49 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// modified from http://codepen.io/enxaneta/pen/jbVLGb/, see copyright there
import React, { Component } from "react";
class SineWave extends Component {
componentDidMount() {
this.ctx = this.node.getContext("2d");
const { width, height } = this.node.getBoundingClientRect();
this.width = width;
this.height = height;
this.renderCanvas(true);
}
componentDidUpdate(prevProps) {
if (!prevProps.draw && this.props.draw) {
this.renderCanvas();
}
}
renderCanvas(force) {
const { ctx, width, height } = this;
let phi = 0;
let frames = 0;
ctx.lineWidth = 4;
const draw = () => {
const amplitude = height * this.props.amplitude;
const frequency = this.props.frequency / 2;
const offset = (height - amplitude) / 2;
frames++;
phi = frames / 30;
ctx.clearRect(0, 0, width, height);
ctx.strokeStyle = "white";
ctx.moveTo(0, height);
ctx.beginPath();
for (var x = 0; x < width; x++) {
let y = Math.sin(x * frequency + phi) * amplitude / 2 + amplitude / 2;
ctx.lineTo(x, y + offset); // 40 = offset
}
ctx.stroke();
if (this.props.draw) {
window.requestAnimationFrame(draw);
}
};
if (force || this.props.draw) {
window.requestAnimationFrame(draw);
}
}
render() {
const { width, height } = this.props;
return <canvas ref={n => (this.node = n)} width={width} height={height} />;
}
}
export default SineWave;