forked from lindelof/particles-bg
/
Canvas.jsx
executable file
·103 lines (86 loc) · 2.47 KB
/
Canvas.jsx
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import React from "react";
import RAFManager from "raf-manager";
export default class Canvas extends React.Component {
constructor(props) {
super(props);
this.size = { width: 0, height: 0 };
this.canvasRef = React.createRef();
}
componentDidMount() {
setTimeout(() => {
this.initCanvas();
window.addEventListener("resize", this.resize);
}, 100);
const canvas = this.canvasRef.current;
this.props.onCanvasDidMount && this.props.onCanvasDidMount(canvas);
}
initCanvas() {
const canvas = this.canvasRef.current;
if (this.props.globalCompositeOperation) {
const context = canvas.getContext("2d");
context.globalCompositeOperation = this.props.globalCompositeOperation;
}
const { width, height } = this.setCanvasSize(canvas);
this.heartbeatDetectionCanvasSize(canvas);
this.props.onCanvasInited(canvas, width, height);
}
heartbeatDetectionCanvasSize(canvas) {
this.interval = setInterval(() => {
if (this.canvasRef.current) {
const newHeight = this.canvasRef.current.clientHeight;
if (newHeight !== this.size.height) {
const { width, height } = this.setCanvasSize(canvas);
this.props.onResize && this.props.onResize(width, height);
}
}
}, 1000 / 10);
}
componentWillUnmount() {
window.clearInterval(this.interval);
window.removeEventListener("resize", this.resize);
}
resize = () => {
const canvas = this.canvasRef.current;
const { width, height } = this.setCanvasSize(canvas);
this.props.onResize && this.props.onResize(width, height);
}
setCanvasSize(canvas) {
const width = this.canvasRef.current.clientWidth;
const height = this.canvasRef.current.clientHeight;
this.size.width = width;
this.size.height = height;
canvas.width = width;
canvas.height = height;
return { width, height };
}
handleWaypointEnter() {
RAFManager.start();
}
handleWaypointLeave() {
RAFManager.stop();
}
getStyle() {
let style = { width: "100%", height: "100%" };
if (this.props.bg) {
style = Object.assign(style, {
position: "absolute",
zIndex: -1,
top: 0,
left: 0
});
}
return style;
}
handleMouseDown = e => {
this.props.onMouseDown && this.props.onMouseDown(e);
}
render() {
return (
<canvas
ref={this.canvasRef}
onMouseDown={this.handleMouseDown}
style={this.getStyle()}
/>
);
}
}