PaintArea.js (1751B)
1 import React, { Component } from 'react' 2 import { rgb, getPixel } from './Utils' 3 4 /** 5 * Expects props: 6 * onTool = (x, y) => {} 7 * Callback for when a cell is clicked 8 * 9 * data = [[]] 10 * 3d array - rows, cells, RGB value for each cell 11 */ 12 export default class PaintArea extends Component { 13 constructor(props) { 14 super(props) 15 this.handleMouseMove = this.handleMouseMove.bind(this) 16 this._onMouseDown = this._onMouseDown.bind(this) 17 this._onMouseUp = this._onMouseUp.bind(this) 18 this.state = { 19 mouseDown: false 20 } 21 } 22 23 _onMouseDown() { 24 this.setState({ mouseDown: true }) 25 } 26 27 _onMouseUp() { 28 this.setState({ mouseDown: false }) 29 } 30 31 componentWillMount() { 32 document.addEventListener('mousedown', this._onMouseDown) 33 document.addEventListener('mouseup', this._onMouseUp) 34 } 35 36 componentWillUnmount() { 37 document.removeEventListener('mousedown', this._onMouseDown) 38 document.removeEventListener('mouseup', this._onMouseUp) 39 } 40 41 handleMouseMove(x, y) { 42 if (this.state.mouseDown) { 43 this.props.onTool(x, y) 44 } 45 } 46 47 render() { 48 let data = this.props.data 49 let height = data[0] ? data[0].length : 0 50 let cells = [] 51 for (var y=height-1; y>=0; y--) { 52 for (var x=0; x<data.length; x++) { 53 let {r, g, b} = rgb(getPixel(x, y, data)) 54 let ix = x 55 let iy = y 56 cells.push(<div 57 className="paintAreaCell" 58 onMouseMove={() => this.handleMouseMove(ix, iy)} 59 onClick={() => this.props.onTool(ix, iy)} 60 style={{ 61 background: `rgb(${r},${g},${b})` 62 }} 63 key={(ix * 100000) + iy}/>) 64 } 65 } 66 67 return ( 68 <div className="paint"> 69 {cells} 70 </div> 71 ) 72 } 73 }