Skip to content

Instantly share code, notes, and snippets.

@herbert1228
Created January 30, 2019 09:17
Show Gist options
  • Save herbert1228/2011fca9924713cebd2bd747e583027a to your computer and use it in GitHub Desktop.
Save herbert1228/2011fca9924713cebd2bd747e583027a to your computer and use it in GitHub Desktop.
import React, { Component } from 'react';
import {connection} from './interface/connection'
const style = {
canvas: {
style: {
left: '0px',
top: '0px'
},
border: 'solid 1px',
transform: 'translateX(-50%) translateY(-50%)',
position: 'absolute',
top: '50%',
left: '50%'
}
}
export default class App extends Component {
state = {
counter: 0,
dragging: false,
radius: 3
}
componentDidMount() {
this.canvas = document.getElementById("user-canvas")
this.ctx = this.canvas.getContext('2d');
this.ctx.lineWidth = this.state.radius * 2
this.ctx.fillStyle = "red"
this.ctx.strokeStyle = "red"
}
handleMouseMove = (e) => {
const [x, y] = this.getMousePosition(e)
if (this.state.dragging) {
// console.log(e.clientX, e.clientY)
this.ctx.globalCompositeOperation="source-over"
this.ctx.lineTo(x, y)
this.ctx.stroke()
this.ctx.beginPath()
this.ctx.arc(x, y, this.state.radius, 0, Math.PI * 2)
this.ctx.fill()
this.ctx.beginPath()
this.ctx.moveTo(x, y)
}
}
handleMouseUp = () => {
this.setState({dragging: false})
// connection.cast("pen draw", drawMessage) // broadcast draw message to everyone in class
}
handleMouseDown = (e) => {
this.setState({dragging: true})
this.ctx.beginPath()
}
getMousePosition(e) {
const { top, left } = this.canvas.getBoundingClientRect();
return [ e.clientX - left, e.clientY - top ]
}
render() {
return (
<canvas
id = {
"user-canvas"
}
height="340"
width="600"
style={style.canvas}
ref = {(canvas) => this.canvasRef = canvas}
onMouseMove={this.handleMouseMove}
onMouseUp={this.handleMouseUp}
onMouseDown={this.handleMouseDown}
></canvas>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment