├── .babelrc ├── .editorconfig ├── .eslintrc ├── .gitignore ├── .idea ├── dictionaries │ └── svrcek.xml ├── jsLibraryMappings.xml └── vcs.xml ├── .npmignore ├── LICENSE ├── README.md ├── circle.yml ├── docs ├── frog.gif └── react3.gif ├── example ├── .babelrc ├── SketchExample.jsx ├── build │ └── bundle.js ├── index.html ├── index.js ├── package.json ├── server.js └── webpack.config.js ├── package.json └── src ├── SketchPad.jsx ├── index.js └── tools ├── Ellipse.js ├── Line.js ├── Pencil.js ├── Rectangle.js └── index.js /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets":["es2015","react"], 3 | "plugins":[ 4 | "transform-class-properties", 5 | "transform-object-rest-spread" 6 | ] 7 | } 8 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig helps developers define and maintain consistent 2 | # coding styles between different editors and IDEs. 3 | # editorconfig.org 4 | 5 | root = true 6 | 7 | [*] 8 | 9 | # We recommend you to keep these unchanged. 10 | charset = utf-8 11 | end_of_line = lf 12 | indent_size = 2 13 | indent_style = space 14 | insert_final_newline = true 15 | trim_trailing_whitespace = true 16 | 17 | [package.json] 18 | indent_style = space 19 | indent_size = 2 20 | 21 | [*.md] 22 | trim_trailing_whitespace = false 23 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "eslint-config-airbnb", 3 | "env": { 4 | "browser": true, 5 | "node": true, 6 | "mocha": true 7 | }, 8 | "ecmaFeatures": { 9 | "destructing": true, 10 | "classes": true 11 | }, 12 | "rules": { 13 | "no-param-reassign": 0, 14 | "consistent-return": 0, 15 | "import/default": 0, 16 | "import/no-duplicates": 0, 17 | "import/named": 0, 18 | "import/namespace": 0, 19 | "import/no-unresolved": 0, 20 | "import/no-named-as-default": 2, 21 | "comma-dangle": 0, 22 | // not sure why airbnb turned this on. gross! 23 | "indent": [2, 2, {"SwitchCase": 1}], 24 | "no-console": 0, 25 | "no-alert": 0, 26 | "max-len":[2,140] 27 | }, 28 | "plugins": [ 29 | "import" 30 | ], 31 | "parser": "babel-eslint" 32 | } 33 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | lib/ 3 | npm-debug.log 4 | .idea 5 | -------------------------------------------------------------------------------- /.idea/dictionaries/svrcek.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /.idea/jsLibraryMappings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | src 2 | example 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Michal Svrček 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # react-sketchpad 2 | Sketch pad created with canvas 3 | 4 | ## Why I built this? 5 | 6 | 1. to learn 7 | 2. to learn 8 | 3. to learn 9 | 4. just have fun? :D 10 | 11 | ## Example: 12 | 13 | ![Draw little frog](docs/frog.gif?raw=true "Draw little frog") 14 | 15 | ![Draw react logo with aniamted pencil](docs/react3.gif?raw=true "Draw react logo with aniamted pencil") 16 | 17 | There was websocket used in this gifs, which is not part of example. To make it work with syncing just run this little websocket server 18 | 19 | ```js 20 | import Server from 'socket.io'; 21 | const io = new Server().attach(12346); 22 | 23 | io.on('connection', (socket) => { 24 | socket.on('addItem', (data) => { 25 | console.log(data); 26 | socket.broadcast.emit('addItem', data); 27 | }); 28 | }); 29 | ``` 30 | 31 | ## API: 32 | 33 | |Attribute |Type |Default Value |Description | 34 | |--- |--- |--- |--- | 35 | | width | number | 500 | width of canvas in pixels | 36 | | height | number | 500 | height of the canvas in pixels | 37 | | items | array | - | array of items to draw in canvas | 38 | | animate | bool | true | few tools, for example pencil, can be animated when drawn | 39 | | canvasClassName | string | .canvas | css class of canvas | 40 | | color | string | #000 | primary drawing color | 41 | | fillColor | string | `""` | color used for filling items like circle or rectangle, empty string is no filling | 42 | | size | number | 5 | size of the item | 43 | | tool | string | TOOL_PENCIL | currently used tool from the map | 44 | | toolsMap | object | object map | keys are tool names, values are tool functions, by default Pencil, Line, Circle and Rectangle tools are available | 45 | | onItemStart | func | - | function to be executed on item start, most of the time first argument is item | 46 | | onEveryItemChange | func | - | function to be executed on item change, most of the time first argument is item, other arguments describe changes | 47 | | onDebouncedItemChange | func | - | function to be executed in interval on item change, most of the time first argument is item, other arguments describe batched changes | 48 | | onCompleteItem | func | - | function to be executed on item end, most of the time first argument is item | 49 | | debounceTime | number | 1000 | how often onDebouncedItemChange will be called | 50 | -------------------------------------------------------------------------------- /circle.yml: -------------------------------------------------------------------------------- 1 | machine: 2 | node: 3 | version: 4.0 4 | environment: 5 | CONTINUOUS_INTEGRATION: true 6 | 7 | dependencies: 8 | cache_directories: 9 | - node_modules 10 | override: 11 | - npm prune && npm install 12 | -------------------------------------------------------------------------------- /docs/frog.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/svrcekmichal/react-sketchpad/b4006c6fdddbdc52cecd6db4c9e4b511cca9ff80/docs/frog.gif -------------------------------------------------------------------------------- /docs/react3.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/svrcekmichal/react-sketchpad/b4006c6fdddbdc52cecd6db4c9e4b511cca9ff80/docs/react3.gif -------------------------------------------------------------------------------- /example/.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets":["es2015","react"], 3 | "plugins":[ 4 | "transform-class-properties", 5 | "transform-object-rest-spread" 6 | ] 7 | } 8 | -------------------------------------------------------------------------------- /example/SketchExample.jsx: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import { SketchPad, TOOL_PENCIL, TOOL_LINE, TOOL_RECTANGLE, TOOL_ELLIPSE } from './../src'; 3 | import IO from 'socket.io-client' 4 | 5 | const wsClient = IO(`ws://127.0.0.1:12346`); 6 | 7 | export default class SketchExample extends Component 8 | { 9 | socket = null; 10 | 11 | constructor(props) { 12 | super(props); 13 | 14 | this.state = { 15 | tool:TOOL_PENCIL, 16 | size: 2, 17 | color: '#000000', 18 | fill: false, 19 | fillColor: '#444444', 20 | items: [] 21 | } 22 | } 23 | 24 | componentDidMount() { 25 | wsClient.on('addItem', item => this.setState({items: this.state.items.concat([item])})); 26 | } 27 | 28 | render() { 29 | const { tool, size, color, fill, fillColor, items } = this.state; 30 | return ( 31 |
32 |

React SketchPad

33 |
34 | wsClient.emit('addItem', i)} 44 | /> 45 |
46 |
47 |
48 | 53 | 58 | 63 | 68 |
69 |
70 | 71 | this.setState({size: parseInt(e.target.value)})} /> 72 |
73 |
74 | 75 | this.setState({color: e.target.value})} /> 76 |
77 | {(this.state.tool == TOOL_ELLIPSE || this.state.tool == TOOL_RECTANGLE) ? 78 |
79 | 80 | this.setState({fill: e.target.checked})} /> 82 | {fill ? 83 | 84 | this.setState({fillColor: e.target.value})} /> 85 | : ''} 86 |
: ''} 87 |
88 |
89 | ); 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /example/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /example/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { render } from 'react-dom'; 3 | import SketchExample from './SketchExample'; 4 | 5 | render(( 6 | 7 | ), document.getElementById('app')); 8 | -------------------------------------------------------------------------------- /example/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-sketchpad-example", 3 | "version": "0.0.1", 4 | "description": "Sketch pad created with canvas", 5 | "main": "index.js", 6 | "scripts": { 7 | "start": "node ./server.js", 8 | "build": "webpack" 9 | }, 10 | "repository": { 11 | "type": "git", 12 | "url": "git+https://github.com/svrcekmichal/react-sketchpad.git" 13 | }, 14 | "keywords": [], 15 | "author": "", 16 | "license": "MIT", 17 | "bugs": { 18 | "url": "https://github.com/svrcekmichal/react-sketchpad/issues" 19 | }, 20 | "homepage": "https://github.com/svrcekmichal/react-sketchpad#readme", 21 | "dependencies": { 22 | "babel-cli": "^6.7.5", 23 | "babel-loader": "^6.2.4", 24 | "babel-plugin-transform-class-properties": "^6.6.0", 25 | "babel-plugin-transform-object-rest-spread": "^6.6.5", 26 | "babel-preset-es2015": "^6.6.0", 27 | "babel-preset-react": "^6.5.0", 28 | "react": "^0.14.0 || ^15.0.0", 29 | "react-dom": "^0.14.0 || ^15.0.0", 30 | "react-hot-loader": "^1.3.0", 31 | "socket.io-client": "^1.4.5", 32 | "uuid": "^2.0.0", 33 | "webpack": "^1.12.15", 34 | "webpack-dev-server": "^1.14.1" 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /example/server.js: -------------------------------------------------------------------------------- 1 | var webpack = require('webpack'); 2 | var WebpackDevServer = require('webpack-dev-server'); 3 | var config = require('./webpack.config'); 4 | 5 | new WebpackDevServer(webpack(config), { 6 | publicPath: config.output.publicPath, 7 | hot: true, 8 | historyApiFallback: true, 9 | colors:true, 10 | contentBase: __dirname 11 | }).listen(12345, '127.0.0.1', function (err, result) { 12 | if (err) { 13 | return console.log(err); 14 | } 15 | 16 | console.log('Listening at http://127.0.0.1:12345/'); 17 | }); 18 | -------------------------------------------------------------------------------- /example/webpack.config.js: -------------------------------------------------------------------------------- 1 | var path = require('path'); 2 | var webpack = require( "webpack" ); 3 | 4 | module.exports = { 5 | devtool: 'eval', 6 | entry: { 7 | app: [ 8 | 'webpack-dev-server/client?http://127.0.0.1:12345', 9 | 'webpack/hot/only-dev-server', 10 | path.join(__dirname, 'index.js') 11 | ] 12 | }, 13 | output: { 14 | path: path.join(__dirname, 'build'), 15 | publicPath: '/build', 16 | filename: 'bundle.js' 17 | }, 18 | plugins: [ 19 | new webpack.HotModuleReplacementPlugin(), 20 | ], 21 | progress: true, 22 | module: { 23 | loaders: [{ 24 | test: /\.jsx?$/, 25 | loaders: ['react-hot','babel'], 26 | exclude: path.join(__dirname, 'node_modules') 27 | }] 28 | }, 29 | resolve: { 30 | root: path.join(__dirname, 'node_modules'), 31 | extensions: ['', '.js', '.jsx'] 32 | }, 33 | resolveLoader: { 34 | root: path.join(__dirname, 'node_modules') 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-sketchpad", 3 | "version": "0.0.3", 4 | "description": "Sketch pad created with canvas", 5 | "main": "index.js", 6 | "scripts": { 7 | "prepublish": "npm run lint && npm run build", 8 | "build": "babel ./src -d ./lib --ignore '__tests__'", 9 | "lint": "eslint -c .eslintrc src", 10 | "lint:fix": "eslint -c .eslintrc src --fix" 11 | }, 12 | "repository": { 13 | "type": "git", 14 | "url": "git+https://github.com/svrcekmichal/react-sketchpad.git" 15 | }, 16 | "keywords": [], 17 | "author": "", 18 | "license": "MIT", 19 | "bugs": { 20 | "url": "https://github.com/svrcekmichal/react-sketchpad/issues" 21 | }, 22 | "homepage": "https://github.com/svrcekmichal/react-sketchpad#readme", 23 | "dependencies": { 24 | "react": "^0.14.0 || ^15.0.0", 25 | "react-dom": "^0.14.0 || ^15.0.0", 26 | "uuid": "^2.0.0" 27 | }, 28 | "devDependencies": { 29 | "babel-cli": "^6.7.5", 30 | "babel-eslint": "^6.0.2", 31 | "babel-plugin-transform-class-properties": "^6.6.0", 32 | "babel-plugin-transform-object-rest-spread": "^6.6.5", 33 | "babel-preset-es2015": "^6.6.0", 34 | "babel-preset-react": "^6.5.0", 35 | "eslint": "^2.7.0", 36 | "eslint-config-airbnb": "^7.0.0", 37 | "eslint-plugin-import": "^1.4.0", 38 | "eslint-plugin-jsx-a11y": "^0.6.2", 39 | "eslint-plugin-react": "^4.3.0" 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/SketchPad.jsx: -------------------------------------------------------------------------------- 1 | import React, {Component, PropTypes} from 'react'; 2 | import { findDOMNode } from 'react-dom' 3 | import { Pencil, TOOL_PENCIL, Line, TOOL_LINE, Ellipse, TOOL_ELLIPSE, Rectangle, TOOL_RECTANGLE } from './tools' 4 | 5 | export const toolsMap = { 6 | [TOOL_PENCIL]: Pencil, 7 | [TOOL_LINE]: Line, 8 | [TOOL_RECTANGLE]: Rectangle, 9 | [TOOL_ELLIPSE]: Ellipse 10 | }; 11 | 12 | export default class SketchPad extends Component { 13 | 14 | tool = null; 15 | interval = null; 16 | 17 | static propTypes = { 18 | width: PropTypes.number, 19 | height: PropTypes.number, 20 | items: PropTypes.array.isRequired, 21 | animate: PropTypes.bool, 22 | canvasClassName: PropTypes.string, 23 | color: PropTypes.string, 24 | fillColor: PropTypes.string, 25 | size: PropTypes.number, 26 | tool: PropTypes.string, 27 | toolsMap: PropTypes.object, 28 | onItemStart: PropTypes.func, // function(stroke:Stroke) { ... } 29 | onEveryItemChange: PropTypes.func, // function(idStroke:string, x:number, y:number) { ... } 30 | onDebouncedItemChange: PropTypes.func, // function(idStroke, points:Point[]) { ... } 31 | onCompleteItem: PropTypes.func, // function(stroke:Stroke) { ... } 32 | debounceTime: PropTypes.number, 33 | }; 34 | 35 | static defaultProps = { 36 | width: 500, 37 | height: 500, 38 | color: '#000', 39 | size: 5, 40 | fillColor: '', 41 | canvasClassName: 'canvas', 42 | debounceTime: 1000, 43 | animate: true, 44 | tool: TOOL_PENCIL, 45 | toolsMap 46 | }; 47 | 48 | constructor(props) { 49 | super(props); 50 | this.initTool = this.initTool.bind(this); 51 | this.onMouseDown = this.onMouseDown.bind(this); 52 | this.onMouseMove = this.onMouseMove.bind(this); 53 | this.onDebouncedMove = this.onDebouncedMove.bind(this); 54 | this.onMouseUp = this.onMouseUp.bind(this); 55 | } 56 | 57 | componentDidMount() { 58 | this.canvas = findDOMNode(this.canvasRef); 59 | this.ctx = this.canvas.getContext('2d'); 60 | this.initTool(this.props.tool); 61 | } 62 | 63 | componentWillReceiveProps({tool, items}) { 64 | items 65 | .filter(item => this.props.items.indexOf(item) === -1) 66 | .forEach(item => { 67 | this.initTool(item.tool); 68 | this.tool.draw(item, this.props.animate); 69 | }); 70 | this.initTool(tool); 71 | } 72 | 73 | initTool(tool) { 74 | this.tool = this.props.toolsMap[tool](this.ctx); 75 | } 76 | 77 | onMouseDown(e) { 78 | const data = this.tool.onMouseDown(...this.getCursorPosition(e), this.props.color, this.props.size, this.props.fillColor); 79 | data && data[0] && this.props.onItemStart && this.props.onItemStart.apply(null, data); 80 | if (this.props.onDebouncedItemChange) { 81 | this.interval = setInterval(this.onDebouncedMove, this.props.debounceTime); 82 | } 83 | } 84 | 85 | onDebouncedMove() { 86 | if (typeof this.tool.onDebouncedMouseMove == 'function' && this.props.onDebouncedItemChange) { 87 | this.props.onDebouncedItemChange.apply(null, this.tool.onDebouncedMouseMove()); 88 | } 89 | } 90 | 91 | onMouseMove(e) { 92 | const data = this.tool.onMouseMove(...this.getCursorPosition(e)); 93 | data && data[0] && this.props.onEveryItemChange && this.props.onEveryItemChange.apply(null, data); 94 | } 95 | 96 | onMouseUp(e) { 97 | const data = this.tool.onMouseUp(...this.getCursorPosition(e)); 98 | data && data[0] && this.props.onCompleteItem && this.props.onCompleteItem.apply(null, data); 99 | if (this.props.onDebouncedItemChange) { 100 | clearInterval(this.interval); 101 | this.interval = null; 102 | } 103 | } 104 | 105 | getCursorPosition(e) { 106 | const {top, left} = this.canvas.getBoundingClientRect(); 107 | return [ 108 | e.clientX - left, 109 | e.clientY - top 110 | ]; 111 | } 112 | 113 | render() { 114 | const {width, height, canvasClassName} = this.props; 115 | return ( 116 | { this.canvasRef = canvas; }} 118 | className={canvasClassName} 119 | onMouseDown={this.onMouseDown} 120 | onMouseMove={this.onMouseMove} 121 | onMouseOut={this.onMouseUp} 122 | onMouseUp={this.onMouseUp} 123 | width={width} 124 | height={height} 125 | /> 126 | ) 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | export { 2 | default as SketchPad, 3 | toolsMap 4 | } from './SketchPad'; 5 | 6 | // TOOLS 7 | export { 8 | Pencil, 9 | TOOL_PENCIL, 10 | Line, 11 | TOOL_LINE, 12 | Ellipse, 13 | TOOL_ELLIPSE, 14 | Rectangle, 15 | TOOL_RECTANGLE 16 | } from './tools'; 17 | -------------------------------------------------------------------------------- /src/tools/Ellipse.js: -------------------------------------------------------------------------------- 1 | import { v4 } from 'uuid'; 2 | 3 | export const TOOL_ELLIPSE = 'ellipse'; 4 | 5 | export default (context) => { 6 | let ellipse = null; 7 | let imageData = null; 8 | 9 | const onMouseDown = (x, y, color, size, fill) => { 10 | ellipse = { 11 | id: v4(), 12 | tool: TOOL_ELLIPSE, 13 | color, 14 | size, 15 | fill, 16 | start: { x, y }, 17 | end: null 18 | }; 19 | imageData = context.getImageData(0, 0, context.canvas.clientWidth, context.canvas.clientHeight); 20 | return [ellipse]; 21 | }; 22 | 23 | const drawEllipsePolifyll = (centerX, centerY, radiusX, radiusY) => { 24 | let xPos; 25 | let yPos; 26 | let i = 0; 27 | for (i; i < 2 * Math.PI; i += 0.01) { 28 | xPos = centerX - (radiusY * Math.sin(i)) * Math.sin(0) + (radiusX * Math.cos(i)) * Math.cos(0); 29 | yPos = centerY + (radiusX * Math.cos(i)) * Math.sin(0) + (radiusY * Math.sin(i)) * Math.cos(0); 30 | if (i === 0) { 31 | context.moveTo(xPos, yPos); 32 | } else { 33 | context.lineTo(xPos, yPos); 34 | } 35 | } 36 | }; 37 | 38 | const drawEllipse = (item, mouseX, mouseY) => { 39 | const startX = mouseX < item.start.x ? mouseX : item.start.x; 40 | const startY = mouseY < item.start.y ? mouseY : item.start.y; 41 | const endX = mouseX >= item.start.x ? mouseX : item.start.x; 42 | const endY = mouseY >= item.start.y ? mouseY : item.start.y; 43 | const radiusX = (endX - startX) * 0.5; 44 | const radiusY = (endY - startY) * 0.5; 45 | const centerX = startX + radiusX; 46 | const centerY = startY + radiusY; 47 | 48 | context.save(); 49 | context.beginPath(); 50 | context.lineWidth = item.size; 51 | context.strokeStyle = item.color; 52 | context.fillStyle = item.fill; 53 | 54 | if (typeof context.ellipse === 'function') { 55 | context.ellipse(centerX, centerY, radiusX, radiusY, 0, 0, 2 * Math.PI); 56 | } else { 57 | drawEllipsePolifyll(centerX, centerY, radiusX, radiusY); 58 | } 59 | context.stroke(); 60 | if (item.fill) context.fill(); 61 | context.closePath(); 62 | context.restore(); 63 | }; 64 | 65 | const onMouseMove = (x, y) => { 66 | if (!ellipse) return; 67 | context.putImageData(imageData, 0, 0); 68 | drawEllipse(ellipse, x, y); 69 | }; 70 | 71 | const onMouseUp = (x, y) => { 72 | if (!ellipse) return; 73 | onMouseMove(x, y); 74 | const item = ellipse; 75 | imageData = null; 76 | ellipse = null; 77 | item.end = { x, y }; 78 | return [item]; 79 | }; 80 | 81 | const draw = (item) => drawEllipse(item, item.end.x, item.end.y); 82 | 83 | return { 84 | onMouseDown, 85 | onMouseMove, 86 | onMouseUp, 87 | draw 88 | }; 89 | }; 90 | -------------------------------------------------------------------------------- /src/tools/Line.js: -------------------------------------------------------------------------------- 1 | import { v4 } from 'uuid'; 2 | 3 | export const TOOL_LINE = 'line'; 4 | 5 | export default (context) => { 6 | let line = null; 7 | let imageData = null; 8 | 9 | const onMouseDown = (x, y, color, size) => { 10 | line = { 11 | id: v4(), 12 | tool: TOOL_LINE, 13 | color, 14 | size, 15 | start: { x, y }, 16 | end: null 17 | }; 18 | imageData = context.getImageData(0, 0, context.canvas.clientWidth, context.canvas.clientHeight); 19 | return [line]; 20 | }; 21 | 22 | const drawLine = (item, x, y) => { 23 | context.save(); 24 | context.lineJoin = 'round'; 25 | context.lineCap = 'round'; 26 | context.beginPath(); 27 | context.lineWidth = item.size; 28 | context.strokeStyle = item.color; 29 | context.globalCompositeOperation = 'source-over'; 30 | context.moveTo(item.start.x, item.start.y); 31 | context.lineTo(x, y); 32 | context.closePath(); 33 | context.stroke(); 34 | context.restore(); 35 | }; 36 | 37 | const onMouseMove = (x, y) => { 38 | if (!line) return; 39 | context.putImageData(imageData, 0, 0); 40 | drawLine(line, x, y); 41 | }; 42 | 43 | const onMouseUp = (x, y) => { 44 | if (!line) return; 45 | onMouseMove(x, y); 46 | const item = line; 47 | imageData = null; 48 | line = null; 49 | item.end = { x, y }; 50 | return [item]; 51 | }; 52 | 53 | const draw = item => drawLine(item, item.end.x, item.end.y); 54 | 55 | return { 56 | onMouseDown, 57 | onMouseMove, 58 | onMouseUp, 59 | draw, 60 | }; 61 | }; 62 | -------------------------------------------------------------------------------- /src/tools/Pencil.js: -------------------------------------------------------------------------------- 1 | import { v4 } from 'uuid'; 2 | 3 | export const TOOL_PENCIL = 'pencil'; 4 | 5 | export default (context) => { 6 | let stroke = null; 7 | let points = []; 8 | 9 | const onMouseDown = (x, y, color, size) => { 10 | stroke = { 11 | id: v4(), 12 | tool: TOOL_PENCIL, 13 | color, 14 | size, 15 | points: [{ x, y }] 16 | }; 17 | return [stroke]; 18 | }; 19 | 20 | const drawLine = (item, start, { x, y }) => { 21 | context.save(); 22 | context.lineJoin = 'round'; 23 | context.lineCap = 'round'; 24 | context.beginPath(); 25 | context.lineWidth = item.size; 26 | context.strokeStyle = item.color; 27 | context.globalCompositeOperation = 'source-over'; 28 | context.moveTo(start.x, start.y); 29 | context.lineTo(x, y); 30 | context.closePath(); 31 | context.stroke(); 32 | context.restore(); 33 | }; 34 | 35 | const onMouseMove = (x, y) => { 36 | if (!stroke) return []; 37 | const newPoint = { x, y }; 38 | const start = stroke.points.slice(-1)[0]; 39 | drawLine(stroke, start, newPoint); 40 | stroke.points.push(newPoint); 41 | points.push(newPoint); 42 | 43 | return [stroke]; 44 | }; 45 | 46 | const onDebouncedMouseMove = () => { 47 | const debouncedPoints = points; 48 | points = []; 49 | return [stroke, debouncedPoints]; 50 | }; 51 | 52 | const onMouseUp = (x, y) => { 53 | if (!stroke) return; 54 | onMouseMove(x, y); 55 | points = []; 56 | const item = stroke; 57 | stroke = null; 58 | return [item]; 59 | }; 60 | 61 | const draw = (item, animate) => { 62 | let time = 0; 63 | let i = 0; 64 | const j = item.points.length; 65 | for (i, j; i < j; i++) { 66 | if (!item.points[i - 1]) continue; 67 | if (animate) { 68 | setTimeout(drawLine.bind(null, item, item.points[i - 1], item.points[i]), time); 69 | time += 10; 70 | } else { 71 | drawLine(item, item.points[i - 1], item.points[i]); 72 | } 73 | } 74 | }; 75 | 76 | return { 77 | onMouseDown, 78 | onMouseMove, 79 | onDebouncedMouseMove, 80 | onMouseUp, 81 | draw, 82 | }; 83 | }; 84 | -------------------------------------------------------------------------------- /src/tools/Rectangle.js: -------------------------------------------------------------------------------- 1 | import { v4 } from 'uuid'; 2 | 3 | export const TOOL_RECTANGLE = 'rectangle'; 4 | 5 | export default (context) => { 6 | let rectangle = null; 7 | let imageData = null; 8 | 9 | const onMouseDown = (x, y, color, size, fill) => { 10 | rectangle = { 11 | id: v4(), 12 | tool: TOOL_RECTANGLE, 13 | color, 14 | size, 15 | fill, 16 | start: { x, y }, 17 | end: null 18 | }; 19 | imageData = context.getImageData(0, 0, context.canvas.clientWidth, context.canvas.clientHeight); 20 | return [rectangle]; 21 | }; 22 | 23 | const drawRectangle = (item, mouseX, mouseY) => { 24 | const startX = mouseX < item.start.x ? mouseX : item.start.x; 25 | const startY = mouseY < item.start.y ? mouseY : item.start.y; 26 | const widthX = Math.abs(item.start.x - mouseX); 27 | const widthY = Math.abs(item.start.y - mouseY); 28 | 29 | context.beginPath(); 30 | context.lineWidth = item.size; 31 | context.strokeStyle = item.color; 32 | context.fillStyle = item.fill; 33 | context.rect(startX, startY, widthX, widthY); 34 | context.stroke(); 35 | if (item.fill) context.fill(); 36 | }; 37 | 38 | const onMouseMove = (x, y) => { 39 | if (!rectangle) return; 40 | context.putImageData(imageData, 0, 0); 41 | context.save(); 42 | drawRectangle(rectangle, x, y); 43 | context.restore(); 44 | }; 45 | 46 | const onMouseUp = (x, y) => { 47 | if (!rectangle) return; 48 | onMouseMove(x, y); 49 | const item = rectangle; 50 | imageData = null; 51 | rectangle = null; 52 | item.end = { x, y }; 53 | return [item]; 54 | }; 55 | 56 | const draw = item => drawRectangle(item, item.end.x, item.end.y); 57 | 58 | return { 59 | onMouseDown, 60 | onMouseMove, 61 | onMouseUp, 62 | draw, 63 | }; 64 | }; 65 | -------------------------------------------------------------------------------- /src/tools/index.js: -------------------------------------------------------------------------------- 1 | export { 2 | default as Pencil, 3 | TOOL_PENCIL 4 | } from './Pencil'; 5 | 6 | export { 7 | default as Line, 8 | TOOL_LINE 9 | } from './Line'; 10 | 11 | export { 12 | default as Ellipse, 13 | TOOL_ELLIPSE 14 | } from './Ellipse'; 15 | 16 | export { 17 | default as Rectangle, 18 | TOOL_RECTANGLE 19 | } from './Rectangle'; 20 | --------------------------------------------------------------------------------