Created
May 26, 2018 12:02
-
-
Save JohnBra/b37b8316848d2c097c42b2060ff9f1c0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
export default class Canvas extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
canvasWidth: window.innerWidth, | |
canvasHeight: window.innerHeight, | |
mouseX: 0, | |
mouseY: 0, | |
}; | |
} | |
componentDidMount() { | |
window.addEventListener("resize", this.updateDimensions.bind(this)); | |
this.updateDimensions(); | |
this.animate(); | |
} | |
setCanvasRef = (element) => { | |
if (!this.ctx) { | |
this.canvas = element; | |
this.ctx = element.getContext('2d'); | |
} | |
}; | |
handleMouseMove = (e) => { | |
let rect = this.canvas.getBoundingClientRect(); | |
this.setState({mouseX: e.clientX - rect.left, mouseY: e.clientY - rect.top}); | |
}; | |
updateDimensions = () => { | |
this.setState({canvasWidth: window.innerWidth, canvasHeight: window.innerHeight}); | |
}; | |
componentWillUnmount() { | |
this.stopAnimate(); | |
} | |
animate() { | |
//check if canvas component is referenced and _frameId is undefined | |
if (this.ctx && !this._frameId) | |
this._frameId = window.requestAnimationFrame(this.loop); | |
} | |
loop = () => { | |
let { mouseX, mouseY, canvasWidth, canvasHeight } = this.state; | |
//clear the canvas | |
this.ctx.fillStyle = 'rgba(255, 255, 255, 1)'; | |
this.ctx.fillRect(0, 0, canvasWidth, canvasHeight); | |
//draw something | |
this.ctx.fillStyle = "#344AF7"; | |
this.ctx.fillRect(mouseX - 25, mouseY - 25, 50, 50); | |
//set up next iteration of the loop | |
this._frameId = window.requestAnimationFrame(this.loop) | |
}; | |
stopAnimate() { | |
window.cancelAnimationFrame( this._frameId ); | |
} | |
render() { | |
let { canvasWidth, canvasHeight } = this.state; | |
return ( | |
<canvas onMouseMove={this.handleMouseMove.bind(this)} ref={this.setCanvasRef} width={canvasWidth} height={canvasHeight}/> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment