├── .babelrc ├── .eslintrc ├── .github └── ISSUE_TEMPLATE │ ├── bug_report.md │ ├── custom.md │ └── feature_request.md ├── .gitignore ├── .npmignore ├── .prettierignore ├── .prettierrc ├── .storybook ├── addons.js ├── config.js └── webpack.config.js ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── package-lock.json ├── package.json ├── src ├── ReactPainter.tsx ├── helpers │ ├── canvasHelpers.ts │ ├── eventHelpers.ts │ ├── importImageHelpers.ts │ ├── miscHelpers.ts │ ├── objectUrlHelpers.ts │ └── saveCanvasHelpers.ts └── index.ts ├── stories ├── index.stories.js └── storybookComponent.jsx ├── test └── typescript.tsx ├── tsconfig.json └── tslint.json /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | [ 4 | "env", 5 | { 6 | "targets": { 7 | "browsers": ["last 2 versions", "safari >= 7"] 8 | } 9 | } 10 | ], 11 | "stage-2", 12 | "react" 13 | ] 14 | } 15 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "react-app" 3 | } 4 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/custom.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Custom issue template 3 | about: Describe this issue template's purpose here. 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | 11 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | npm-error.log 3 | dist 4 | storybook-static 5 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aml2610/react-painter/25e183086fafbadfd46bff39c46d0c04697cfbd7/.npmignore -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | dist 2 | node_modules 3 | .storybook 4 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aml2610/react-painter/25e183086fafbadfd46bff39c46d0c04697cfbd7/.prettierrc -------------------------------------------------------------------------------- /.storybook/addons.js: -------------------------------------------------------------------------------- 1 | import "@storybook/addon-actions/register"; 2 | import "@storybook/addon-links/register"; 3 | import "@storybook/addon-knobs/register"; 4 | -------------------------------------------------------------------------------- /.storybook/config.js: -------------------------------------------------------------------------------- 1 | import { configure } from '@storybook/react'; 2 | 3 | // automatically import all files ending in *.stories.js 4 | const req = require.context('../stories', true, /.stories.js$/); 5 | function loadStories() { 6 | req.keys().forEach(filename => req(filename)); 7 | } 8 | 9 | configure(loadStories, module); 10 | -------------------------------------------------------------------------------- /.storybook/webpack.config.js: -------------------------------------------------------------------------------- 1 | const genDefaultConfig = require('@storybook/react/dist/server/config/defaults/webpack.config.js'); 2 | module.exports = (baseConfig, env) => { 3 | const config = genDefaultConfig(baseConfig, env); 4 | // Extend it as you need. 5 | // For example, add typescript loader: 6 | config.module.rules.push({ 7 | test: /\.(ts|tsx)$/, 8 | loader: require.resolve('awesome-typescript-loader') 9 | }); 10 | config.resolve.extensions.push('.ts', '.tsx'); 11 | return config; 12 | }; -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at andrei.longhin1@gmail.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | Pull requests are welcome if you'd like to contribute to this project. 2 | 3 | Before you make a pull request can you please open an issue so we can discuss features added or bugs fixed 4 | prior to any work being done. 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Andrei-Marius Longhin 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-painter 2 | 3 | [![version](https://img.shields.io/npm/v/react-painter.svg)](https://www.npmjs.com/package/react-painter) 4 | ![license](https://img.shields.io/npm/l/react-painter.svg) 5 | 6 | [DEMO](https://aml2610.github.io/react-painter/) 7 | 8 |

0 dependency React component that can be used to draw on a canvas with mouse/touch

9 | 10 |
11 | 12 | ## The problem 13 | 14 | You want simple functionality to allow the user to write/draw on image/blank canvas, then save the output to be uploaded to a server/locally. 15 | 16 | ## The solution 17 | 18 | This is a simple component that utilises HTML5 canvases and the File API. 19 | It uses a render prop which gives you maximum flexibility with a minimal API because you are able to extend functionality and render the result as you wish. 20 | 21 | ## Installation 22 | 23 | This module is distributed via [npm][npm] which is bundled with [node][node] and 24 | should be installed as one of your project's `dependencies`: 25 | 26 | ``` 27 | npm install --save react-painter 28 | ``` 29 | 30 | > This package also depends on `react` and `prop-types`. Make sure they are installed in your project. 31 | 32 | ## Usage 33 | 34 | ```jsx 35 | import { ReactPainter } from 'react-painter'; 36 | 37 | const Drawable = () => ( 38 | console.log(blob)} 42 | render={({ triggerSave, canvas }) => ( 43 |
44 | 45 |
{canvas}
46 |
47 | )} 48 | /> 49 | ); 50 | ``` 51 | 52 | ## Props 53 | 54 | ### height?: number 55 | 56 | > defaults to `300` 57 | 58 | Set the height of the canvas 59 | This value should not be changed after ReactPainter is mounted as it will mess up the resolution. Remount a new instance when the height changed. 60 | 61 | ### width?: number 62 | 63 | > defaults to `300` 64 | 65 | Set the width of the canvas 66 | Similar to height, this value should not be changed after mounted. 67 | 68 | ### initialColor?: string 69 | 70 | > defaults to `#000` 71 | 72 | Set the initial stroke color. 73 | Stroke can be changed dynamically using `setColor`. 74 | 75 | ### initialLineWidth?: number 76 | 77 | > defaults to `5` 78 | 79 | Set the initial stroke line width. 80 | Line width can be changed dynamically using `setLineWidth`. 81 | 82 | ### lineCap?: 'round' | 'butt' | 'square' 83 | 84 | > defaults to `round` 85 | 86 | Set the initial stroke line cap. 87 | Line cap can be changed dynamically using `setLineCap`. 88 | 89 | ### initialLineJoin?: 'round' | 'bevel' | 'miter' 90 | 91 | > defaults to `round` 92 | 93 | Set the initial stroke line join. 94 | Line join type can be changed dynamically using `setLineJoin`. 95 | 96 | ### onSave?: (blob: Blob) => void 97 | 98 | Your handler when the canvas is saved. 99 | 100 | ### image?: File | string 101 | 102 | The image that would takes up the whole canvas. If it is a string, then it should be an URL for an image. 103 | 104 | > Note: It the image is not accessible publicly or via cookies, the image will not be shown. You can check the result via `imageCanDownload` property. 105 | 106 | ### render?: (props: RenderProps) => ReactNode 107 | 108 | This is called with an object. Read more about the properties of the object in the section [Render Prop Function](#render-prop-function). 109 | 110 | > Note: If you do not provide the render function. A canvas element will be mounted as default. However, this is not really useful because you cannot trigger the save of the canvas. 111 | 112 | ## Render Prop Function 113 | 114 | This is where you want to render the canvas and the function to trigger save. It is a regular prop called `render`: `` 115 | The properties of the object passed to this function are listed below. 116 | 117 | ### canvas: ReactNode 118 | 119 | This is the canvas node that you can used to mount in your component. Example: 120 | 121 | ```jsx 122 | ( 124 |
125 |
Awesome heading
126 |
{canvas}
127 |
128 | )} 129 | /> 130 | ``` 131 | 132 | ### triggerSave: () => void 133 | 134 | This is the function that you invoke when you want to save the canvas. 135 | 136 | Example: 137 | 138 | ```jsx 139 | ( 141 |
142 |
Awesome heading
143 |
{canvas}
144 | 145 |
146 | )} 147 | /> 148 | ``` 149 | 150 | ### setColor: (color: string) => void 151 | 152 | Set the color of the line. 153 | 154 | Example: 155 | 156 | ```jsx 157 | ( 159 |
160 |
Awesome heading
161 | setColor(e.target.value)} /> 162 |
{canvas}
163 | 164 |
165 | )} 166 | /> 167 | ``` 168 | 169 | ### setLineWidth: (width: number) => void 170 | 171 | Set the width of the line. 172 | 173 | Example: 174 | 175 | ```jsx 176 | ( 178 |
179 |
Awesome heading
180 | setLineWidth(e.target.value)} /> 181 |
{canvas}
182 | 183 |
184 | )} 185 | /> 186 | ``` 187 | 188 | ### setLineJoin: (type: 'round' | 'bevel' | 'miter') => void 189 | 190 | Set the join type of the line. 191 | 192 | Example: 193 | 194 | ```jsx 195 | ( 197 |
198 |
Awesome heading
199 | 204 |
{canvas}
205 | 206 |
207 | )} 208 | /> 209 | ``` 210 | 211 | ### setLineCap: (type: 'round' | 'butt' | 'square') => void 212 | 213 | Set the cap type of the line. 214 | 215 | Example: 216 | 217 | ```jsx 218 | ( 220 |
221 |
Awesome heading
222 | 227 |
{canvas}
228 | 229 |
230 | )} 231 | /> 232 | ``` 233 | 234 | ### imageCanDownload: boolean 235 | 236 | This properties let you know if the image is inserted successfully. By default it is `null` until the checking of image import is successful. 237 | 238 | Example: 239 | 240 | ```jsx 241 | ( 244 |
245 |
Awesome heading
246 | {imageCanDownload ?

Sorry, the image that you have provided is not accessible.

: null} 247 |
{canvas}
248 | 249 |
250 | )} 251 | ``` 252 | 253 | ### imageDownloadUrl: string; 254 | 255 | This properties is the URL you can use to allow user to download the saved image after invoke `triggerSave`. By default it is `null` until the `triggerSave` is invoked. 256 | 257 | Example: 258 | 259 | ```jsx 260 | ( 262 |
263 |
Awesome heading
264 |
{canvas}
265 | 266 | {imageDownloadUrl ? ( 267 | 268 | Download 269 | 270 | ) : null} 271 |
272 | )} 273 | /> 274 | ``` 275 | 276 | ### getCanvasProps: (any) => CanvasProps; 277 | 278 | Prop getter for advanced use case. If you wish to extend the functionality of ReactPainter by adding additional properties to the canvas/getting the `ref` of the canvas, then call this function with those properties and spread the result of this function to the canvas. 279 | 280 | > Note: Only callback ref is supported. The new `React.createRef` is not supported. 281 | 282 | Example: 283 | 284 | ```jsx 285 | ( 287 |
288 |
Awesome heading
289 |
290 | (this.canvasRef = ref) })} /> 291 |
292 | 293 |
294 | )} 295 | /> 296 | ``` 297 | 298 | > Read more about prop getter in this [article][prop-getter-blog]. 299 | 300 | [npm]: https://www.npmjs.com/ 301 | [node]: https://nodejs.org 302 | [prop-getter-blog]: https://blog.kentcdodds.com/how-to-give-rendering-control-to-users-with-prop-getters-549eaef76acf 303 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-painter", 3 | "version": "0.4.0", 4 | "description": "A React component for drawing in a canvas", 5 | "main": "dist/index.js", 6 | "types": "dist/index.d.ts", 7 | "scripts": { 8 | "lint": "tslint src/**/*.{ts,tsx}", 9 | "prettify": "prettier --write src/**/*.{ts,tsx}", 10 | "build": "tsc --p tsconfig.json", 11 | "prebuild": "rimraf dist", 12 | "prepublish": "npm run build", 13 | "test": "jest", 14 | "storybook": "start-storybook -p 6006", 15 | "build-storybook": "build-storybook", 16 | "deploy-storybook": "storybook-to-ghpages" 17 | }, 18 | "repository": { 19 | "type": "git", 20 | "url": "git+https://github.com/aml2610/react-painter.git" 21 | }, 22 | "keywords": [ 23 | "react", 24 | "canvas", 25 | "drawing" 26 | ], 27 | "author": { 28 | "name": "Andrei-Marius Longhin", 29 | "email": "andrei.longhin1@gmail.com" 30 | }, 31 | "license": "MIT", 32 | "bugs": { 33 | "url": "https://github.com/aml2610/react-painter/issues" 34 | }, 35 | "homepage": "https://github.com/aml2610/react-painter#readme", 36 | "peerDependencies": { 37 | "prop-types": ">=15", 38 | "react": ">=0.14.x" 39 | }, 40 | "devDependencies": { 41 | "@storybook/addon-actions": "^7.6.3", 42 | "@storybook/addon-knobs": "^7.0.2", 43 | "@storybook/addon-links": "^7.6.3", 44 | "@storybook/addons": "^3.4.0", 45 | "@storybook/react": "^7.0.6", 46 | "@storybook/storybook-deployer": "^2.3.0", 47 | "@types/jest": "^22.2.2", 48 | "@types/prop-types": "^15.5.2", 49 | "@types/react": "^16.3.5", 50 | "@types/react-dom": "^16.0.4", 51 | "awesome-typescript-loader": "4.0.0", 52 | "babel-cli": "^6.26.0", 53 | "babel-core": "^6.26.0", 54 | "babel-eslint": "^7.2.3", 55 | "babel-preset-env": "^1.6.1", 56 | "babel-preset-react": "^6.24.1", 57 | "babel-preset-stage-2": "^6.24.1", 58 | "babel-runtime": "^6.26.0", 59 | "canvas-prebuilt": "1.6.11", 60 | "core-js": "^2.5.4", 61 | "eslint": "^4.1.1", 62 | "eslint-config-react-app": "^2.1.0", 63 | "eslint-plugin-flowtype": "^2.46.1", 64 | "eslint-plugin-import": "^2.10.0", 65 | "eslint-plugin-jsx-a11y": "^5.1.1", 66 | "eslint-plugin-react": "^7.7.0", 67 | "jest": "^29.6.1", 68 | "prettier": "^1.19.1", 69 | "prop-types": "^15.6.1", 70 | "react": "16.14.0", 71 | "react-dom": "16.14.0", 72 | "react-testing-library": "^2.1.0", 73 | "rimraf": "^2.6.2", 74 | "ts-jest": "^29.1.1", 75 | "tslint": "^5.9.1", 76 | "tslint-react": "^3.5.1", 77 | "typescript": "^2.8.1" 78 | }, 79 | "dependencies": {}, 80 | "prettier": { 81 | "singleQuote": true, 82 | "printWidth": 90 83 | }, 84 | "jest": { 85 | "transform": { 86 | "^.+\\.tsx?$": "ts-jest" 87 | }, 88 | "testURL": "http://localhost", 89 | "testRegex": "test/.*.(tsx?|jsx?)$", 90 | "moduleFileExtensions": [ 91 | "ts", 92 | "tsx", 93 | "js", 94 | "jsx", 95 | "json", 96 | "node" 97 | ], 98 | "collectCoverageFrom": [ 99 | "src/**/*.tsx", 100 | "src/**/*.ts" 101 | ], 102 | "coverageReporters": [ 103 | "text-summary" 104 | ] 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /src/ReactPainter.tsx: -------------------------------------------------------------------------------- 1 | import * as PropTypes from 'prop-types'; 2 | import * as React from 'react'; 3 | import { canvasToBlob } from './helpers/saveCanvasHelpers'; 4 | import { importImage } from './helpers/importImageHelpers'; 5 | import { extractOffSetFromEvent } from './helpers/eventHelpers'; 6 | import { getCanvasDimensionsScaledForImage } from './helpers/canvasHelpers'; 7 | import { fileToUrl, revokeUrl } from './helpers/objectUrlHelpers'; 8 | import { composeFn } from './helpers/miscHelpers'; 9 | 10 | export type LineJoinType = 'round' | 'bevel' | 'miter'; 11 | export type LineCapType = 'round' | 'butt' | 'square'; 12 | 13 | export interface CanvasProps { 14 | onMouseDown: React.MouseEventHandler; 15 | onTouchStart: React.TouchEventHandler; 16 | onMouseMove: React.MouseEventHandler; 17 | onTouchMove: React.TouchEventHandler; 18 | onMouseUp: React.MouseEventHandler; 19 | onTouchEnd: React.TouchEventHandler; 20 | style: React.CSSProperties; 21 | ref: (ref: HTMLCanvasElement) => void; 22 | } 23 | 24 | export interface PropsGetterInput extends Partial { 25 | [key: string]: any; 26 | } 27 | 28 | export interface PropsGetterResult extends CanvasProps { 29 | [key: string]: any; 30 | } 31 | 32 | export interface RenderProps { 33 | canvas: JSX.Element; 34 | triggerSave: () => void; 35 | getCanvasProps: (props: PropsGetterInput) => PropsGetterResult; 36 | imageCanDownload: boolean; 37 | imageDownloadUrl: string; 38 | setColor: (color: string) => void; 39 | setLineWidth: (width: number) => void; 40 | setLineJoin: (type: LineJoinType) => void; 41 | setLineCap: (type: LineCapType) => void; 42 | } 43 | 44 | export interface ReactPainterProps { 45 | height?: number; 46 | width?: number; 47 | initialColor?: string; 48 | initialLineWidth?: number; 49 | initialLineJoin?: LineJoinType; 50 | initialLineCap?: LineCapType; 51 | onSave?: (blob: Blob) => void; 52 | image?: File | string; 53 | render?: (props: RenderProps) => JSX.Element; 54 | } 55 | 56 | export interface PainterState { 57 | canvasHeight: number; 58 | canvasWidth: number; 59 | imageCanDownload: boolean; 60 | imageDownloadUrl: string; 61 | isDrawing: boolean; 62 | color: string; 63 | lineWidth: number; 64 | lineJoin: LineJoinType; 65 | lineCap: LineCapType; 66 | } 67 | 68 | export class ReactPainter extends React.Component { 69 | static propTypes = { 70 | color: PropTypes.string, 71 | height: PropTypes.number, 72 | image: PropTypes.oneOfType([PropTypes.instanceOf(File), PropTypes.string]), 73 | lineCap: PropTypes.string, 74 | lineJoin: PropTypes.string, 75 | lineWidth: PropTypes.number, 76 | onSave: PropTypes.func, 77 | render: PropTypes.func, 78 | width: PropTypes.number 79 | }; 80 | 81 | static defaultProps: Partial = { 82 | height: 300, 83 | image: undefined, 84 | onSave: () => undefined, 85 | initialColor: '#000', 86 | initialLineCap: 'round', 87 | initialLineJoin: 'round', 88 | initialLineWidth: 5, 89 | width: 300 90 | }; 91 | 92 | canvasRef: HTMLCanvasElement = null; 93 | ctx: CanvasRenderingContext2D = null; 94 | lastX = 0; 95 | lastY = 0; 96 | scalingFactor = 1; 97 | 98 | state: PainterState = { 99 | canvasHeight: 0, 100 | canvasWidth: 0, 101 | color: this.props.initialColor, 102 | imageCanDownload: null, 103 | imageDownloadUrl: null, 104 | isDrawing: false, 105 | lineCap: this.props.initialLineCap, 106 | lineJoin: this.props.initialLineJoin, 107 | lineWidth: this.props.initialLineWidth 108 | }; 109 | 110 | handleMouseDown = (e: React.SyntheticEvent) => { 111 | const { offsetX, offsetY } = extractOffSetFromEvent( 112 | e, 113 | this.scalingFactor, 114 | this.canvasRef 115 | ); 116 | this.lastX = offsetX; 117 | this.lastY = offsetY; 118 | this.setState({ 119 | isDrawing: true 120 | }); 121 | }; 122 | 123 | handleMouseMove = (e: React.SyntheticEvent) => { 124 | const { color, lineWidth, lineCap, lineJoin } = this.state; 125 | if (this.state.isDrawing) { 126 | const { offsetX, offsetY } = extractOffSetFromEvent( 127 | e, 128 | this.scalingFactor, 129 | this.canvasRef 130 | ); 131 | const ctx = this.ctx; 132 | ctx.strokeStyle = color; 133 | ctx.lineWidth = lineWidth * this.scalingFactor; 134 | ctx.lineCap = lineCap; 135 | ctx.lineJoin = lineJoin; 136 | const lastX = this.lastX; 137 | const lastY = this.lastY; 138 | ctx.beginPath(); 139 | ctx.moveTo(lastX, lastY); 140 | ctx.lineTo(offsetX, offsetY); 141 | ctx.stroke(); 142 | this.lastX = offsetX; 143 | this.lastY = offsetY; 144 | } 145 | }; 146 | 147 | handleMouseUp = () => { 148 | this.setState({ 149 | isDrawing: false 150 | }); 151 | }; 152 | 153 | handleSave = () => { 154 | const { onSave } = this.props; 155 | canvasToBlob(this.canvasRef, 'image/png') 156 | .then((blob: Blob) => { 157 | onSave(blob); 158 | this.setState({ 159 | imageDownloadUrl: fileToUrl(blob) 160 | }); 161 | }) 162 | .catch(err => console.error('in ReactPainter handleSave', err)); 163 | }; 164 | 165 | handleSetColor = (color: string) => { 166 | this.setState({ 167 | color 168 | }); 169 | }; 170 | 171 | handleSetLineWidth = (lineWidth: number) => { 172 | this.setState({ 173 | lineWidth 174 | }); 175 | }; 176 | 177 | handleSetLineJoin = (type: 'round' | 'bevel' | 'miter') => { 178 | this.setState({ 179 | lineJoin: type 180 | }); 181 | }; 182 | 183 | handleSetLineCap = (type: 'round' | 'butt' | 'square') => { 184 | this.setState({ 185 | lineCap: type 186 | }); 187 | }; 188 | 189 | initCanvasContext = () => { 190 | const { color, lineWidth, lineJoin, lineCap } = this.state; 191 | this.ctx = this.canvasRef.getContext('2d'); 192 | this.ctx.strokeStyle = color; 193 | this.ctx.lineWidth = lineWidth * this.scalingFactor; 194 | this.ctx.lineJoin = lineJoin; 195 | this.ctx.lineCap = lineCap; 196 | }; 197 | 198 | initCanvasNoImage = (width: number, height: number) => { 199 | this.canvasRef.width = width; 200 | this.canvasRef.height = height; 201 | this.setState({ 202 | canvasHeight: height, 203 | canvasWidth: width 204 | }); 205 | this.initCanvasContext(); 206 | }; 207 | 208 | initCanvasWithImage = (width: number, imgWidth: number, imgHeight: number) => { 209 | const [cvWidth, cvHeight, scalingRatio] = getCanvasDimensionsScaledForImage( 210 | width, 211 | imgWidth, 212 | imgHeight 213 | ); 214 | this.canvasRef.width = imgWidth; 215 | this.canvasRef.height = imgHeight; 216 | this.setState({ 217 | canvasHeight: cvHeight, 218 | canvasWidth: cvWidth 219 | }); 220 | this.scalingFactor = 1 / scalingRatio; 221 | this.initCanvasContext(); 222 | }; 223 | 224 | componentDidMount() { 225 | const { width, height, image } = this.props; 226 | // Disable touch action as we handle it separately 227 | document.body.style.touchAction = 'none'; 228 | if (image) { 229 | importImage(image) 230 | .then(({ img, imgWidth, imgHeight }) => { 231 | this.initCanvasWithImage(width, imgWidth, imgHeight); 232 | this.ctx.drawImage(img, 0, 0, imgWidth, imgHeight); 233 | this.setState({ 234 | imageCanDownload: true 235 | }); 236 | }) 237 | .catch(() => { 238 | this.setState({ 239 | imageCanDownload: false 240 | }); 241 | this.initCanvasNoImage(width, height); 242 | }); 243 | } else { 244 | this.initCanvasNoImage(width, height); 245 | } 246 | } 247 | 248 | componentWillUnmount() { 249 | // Enable touch action again 250 | document.body.style.touchAction = null; 251 | revokeUrl(this.state.imageDownloadUrl); 252 | } 253 | 254 | getCanvasProps = (props: PropsGetterInput = {}): PropsGetterResult => { 255 | const { 256 | onMouseDown, 257 | onTouchStart, 258 | onMouseMove, 259 | onTouchMove, 260 | onMouseUp, 261 | onTouchEnd, 262 | style, 263 | ref, 264 | ...restProps 265 | } = props; 266 | return { 267 | onMouseDown: composeFn(onMouseDown, this.handleMouseDown), 268 | onMouseMove: composeFn(onMouseMove, this.handleMouseMove), 269 | onMouseUp: composeFn(onMouseUp, this.handleMouseUp), 270 | onTouchEnd: composeFn(onTouchEnd, this.handleMouseUp), 271 | onTouchMove: composeFn(onTouchMove, this.handleMouseMove), 272 | onTouchStart: composeFn(onTouchStart, this.handleMouseDown), 273 | ref: composeFn(ref, (canvasRef: HTMLCanvasElement) => { 274 | this.canvasRef = canvasRef; 275 | }), 276 | style: { 277 | height: this.state.canvasHeight, 278 | width: this.state.canvasWidth, 279 | ...style 280 | }, 281 | ...restProps 282 | }; 283 | }; 284 | 285 | render() { 286 | const { render } = this.props; 287 | const { imageCanDownload, imageDownloadUrl } = this.state; 288 | const canvasNode = ; 289 | return typeof render === 'function' 290 | ? render({ 291 | canvas: canvasNode, 292 | getCanvasProps: this.getCanvasProps, 293 | imageCanDownload, 294 | imageDownloadUrl, 295 | setColor: this.handleSetColor, 296 | setLineCap: this.handleSetLineCap, 297 | setLineJoin: this.handleSetLineJoin, 298 | setLineWidth: this.handleSetLineWidth, 299 | triggerSave: this.handleSave 300 | }) 301 | : canvasNode; 302 | } 303 | } 304 | -------------------------------------------------------------------------------- /src/helpers/canvasHelpers.ts: -------------------------------------------------------------------------------- 1 | const getCanvasDimensionsScaledForImage = ( 2 | cvWidth: number, 3 | imageWidth: number, 4 | imageHeight: number 5 | ) => { 6 | if (imageWidth <= cvWidth) { 7 | return [imageWidth, imageHeight, 1]; 8 | } 9 | const scalingRatio = cvWidth / imageWidth; 10 | return [cvWidth, scalingRatio * imageHeight, scalingRatio]; 11 | }; 12 | 13 | export { getCanvasDimensionsScaledForImage }; 14 | -------------------------------------------------------------------------------- /src/helpers/eventHelpers.ts: -------------------------------------------------------------------------------- 1 | import { SyntheticEvent } from 'react'; 2 | 3 | const extractOffSetFromEvent = ( 4 | e: SyntheticEvent, 5 | scalingFactor: number, 6 | canvasRef: HTMLCanvasElement 7 | ) => { 8 | const { 9 | offsetX, 10 | offsetY, 11 | touches, 12 | clientX: mouseClientX, 13 | clientY: mouseClientY 14 | } = e.nativeEvent as any; 15 | // If offset coords are directly on the event we use them 16 | if (offsetX && offsetY) { 17 | return { 18 | offsetX: offsetX * scalingFactor, 19 | offsetY: offsetY * scalingFactor 20 | }; 21 | } 22 | // Otherwise we need to calculate them as difference between (x, y) of event and (left, top) corner of canvas 23 | // We need to check whether user is using a touch device or just the mouse and extract 24 | // the touch/click coords accordingly 25 | const clientX = touches && touches.length ? touches[0].clientX : mouseClientX; 26 | const clientY = touches && touches.length ? touches[0].clientY : mouseClientY; 27 | const rect = canvasRef.getBoundingClientRect(); 28 | const x = (clientX - rect.left) * scalingFactor; 29 | const y = (clientY - rect.top) * scalingFactor; 30 | return { 31 | offsetX: x, 32 | offsetY: y 33 | }; 34 | }; 35 | 36 | export { extractOffSetFromEvent }; 37 | -------------------------------------------------------------------------------- /src/helpers/importImageHelpers.ts: -------------------------------------------------------------------------------- 1 | import { fileToUrl } from './objectUrlHelpers'; 2 | 3 | interface ImportImageResponse { 4 | img: HTMLImageElement | ImageBitmap; 5 | imgWidth: number; 6 | imgHeight: number; 7 | } 8 | 9 | const makeAjaxHeadRequest = ( 10 | url: string, 11 | withCredentials: boolean = false 12 | ): Promise => 13 | new Promise((resolve, reject) => { 14 | try { 15 | const request = new XMLHttpRequest(); 16 | request.open('HEAD', url); 17 | request.timeout = 1000; 18 | request.withCredentials = withCredentials; 19 | request.onreadystatechange = () => { 20 | if (request.readyState === 4) { 21 | if (request.status === 200) { 22 | resolve(request.response); 23 | } else { 24 | reject(request.response); 25 | } 26 | } 27 | }; 28 | request.ontimeout = () => { 29 | reject('Timeout'); 30 | }; 31 | request.send(); 32 | } catch (e) { 33 | reject(e); 34 | } 35 | }); 36 | 37 | const checkImageCrossOriginAllowed = ( 38 | imageUrl: string 39 | ): Promise<{ 40 | anonymous: boolean; 41 | withCredentials: boolean; 42 | }> => 43 | new Promise(resolve => { 44 | Promise.all( 45 | // First try without credentials, then with credentials 46 | // (at the end report which one of the two works - it can be both) 47 | // Have to map, else Promise.all would fail if any request fail 48 | [makeAjaxHeadRequest(imageUrl), makeAjaxHeadRequest(imageUrl, true)].map(promise => 49 | promise 50 | .then(result => ({ 51 | result, 52 | success: true 53 | })) 54 | .catch(error => ({ 55 | error, 56 | success: false 57 | })) 58 | ) 59 | ) 60 | .then(results => 61 | resolve({ 62 | anonymous: results[0].success, 63 | withCredentials: results[1].success 64 | }) 65 | ) 66 | .catch(() => 67 | resolve({ 68 | anonymous: false, 69 | withCredentials: false 70 | }) 71 | ); 72 | }); 73 | 74 | const importImageFromUrl = (url: string): Promise => { 75 | const img = new Image(); 76 | return new Promise((resolve, reject) => { 77 | img.onload = () => { 78 | resolve({ 79 | img, 80 | imgWidth: img.naturalWidth, 81 | imgHeight: img.naturalHeight 82 | }); 83 | }; 84 | checkImageCrossOriginAllowed(url).then(({ anonymous, withCredentials }) => { 85 | if (anonymous || withCredentials) { 86 | img.crossOrigin = anonymous ? 'anonymous' : 'use-credentials'; 87 | img.src = url; 88 | } else { 89 | reject(); 90 | } 91 | }); 92 | }); 93 | }; 94 | 95 | const importImageFromBitmapSrc = (bitmapSrc: File): Promise => 96 | new Promise((resolve, reject) => { 97 | window 98 | .createImageBitmap(bitmapSrc) 99 | .then(img => 100 | resolve({ 101 | img, 102 | imgWidth: img.width, 103 | imgHeight: img.height 104 | }) 105 | ) 106 | .catch(err => reject(err)); 107 | }); 108 | 109 | const importImageFromFile = (file: File): Promise => { 110 | const img = new Image(); 111 | return new Promise(resolve => { 112 | img.onload = () => { 113 | resolve({ 114 | img, 115 | imgWidth: img.naturalWidth, 116 | imgHeight: img.naturalHeight 117 | }); 118 | }; 119 | img.src = fileToUrl(file); 120 | }); 121 | }; 122 | 123 | const importImage = (image: string | File): Promise => { 124 | if (typeof image === 'string') { 125 | return importImageFromUrl(image); 126 | } else if ('createImageBitMap' in window) { 127 | return importImageFromBitmapSrc(image); 128 | } else { 129 | return importImageFromFile(image); 130 | } 131 | }; 132 | 133 | export { importImage }; 134 | -------------------------------------------------------------------------------- /src/helpers/miscHelpers.ts: -------------------------------------------------------------------------------- 1 | type AnyFunction = (...params: any[]) => any; 2 | 3 | const composeFn = (...fns: AnyFunction[]) => (...args: any[]) => 4 | fns.forEach(fn => fn && fn(...args)); 5 | 6 | export { composeFn }; 7 | -------------------------------------------------------------------------------- /src/helpers/objectUrlHelpers.ts: -------------------------------------------------------------------------------- 1 | const fileToUrl = (file: File | Blob): string => { 2 | const url = window.URL || (window as any).webkitURL; 3 | try { 4 | return url.createObjectURL(file); 5 | } catch (e) { 6 | return ''; 7 | } 8 | }; 9 | 10 | const revokeUrl = (objectUrl: string): void => { 11 | try { 12 | window.URL.revokeObjectURL(objectUrl); 13 | } catch (e) { 14 | // fail silently because they is no major disruption to user exp 15 | } 16 | }; 17 | 18 | export { fileToUrl, revokeUrl }; 19 | -------------------------------------------------------------------------------- /src/helpers/saveCanvasHelpers.ts: -------------------------------------------------------------------------------- 1 | const dataUrlToArrayBuffer = (dataURI: string): [string, ArrayBuffer] => { 2 | const type = dataURI.match(/:([^}]*);/)[1]; 3 | const byteString = atob(dataURI.split(',')[1]); 4 | const ia = new Uint8Array(byteString.length); 5 | for (let i = 0; i < byteString.length; i++) { 6 | ia[i] = byteString.charCodeAt(i); 7 | } 8 | return [type, ia.buffer]; 9 | }; 10 | 11 | const canvasToBlob = (canvas: HTMLCanvasElement, type: string): Promise => 12 | new Promise(resolve => { 13 | if (canvas.toBlob) { 14 | canvas.toBlob(blob => resolve(blob), type); 15 | } else { 16 | const dataURL = canvas.toDataURL(type); 17 | const [generatedType, buffer] = dataUrlToArrayBuffer(dataURL); 18 | resolve(new Blob([buffer], { type: generatedType })); 19 | } 20 | }); 21 | 22 | export { canvasToBlob }; 23 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { ReactPainter } from './ReactPainter'; 2 | 3 | export { ReactPainter } from './ReactPainter'; 4 | 5 | export default ReactPainter; 6 | -------------------------------------------------------------------------------- /stories/index.stories.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | 3 | import { storiesOf, forceReRender } from '@storybook/react'; 4 | import { action } from '@storybook/addon-actions'; 5 | import { withKnobs, number, text, button } from '@storybook/addon-knobs/react'; 6 | import { ReactPainter } from '../src'; 7 | import { FramedDiv } from './storybookComponent'; 8 | 9 | const stories = storiesOf('ReactPainter', module); 10 | 11 | stories.addDecorator(withKnobs); 12 | 13 | const styles = { 14 | root: { 15 | display: 'flex', 16 | flexDirection: 'column', 17 | alignItems: 'center' 18 | } 19 | }; 20 | 21 | stories.add('basic', () => ( 22 | ( 27 |
28 |
29 | 30 | 31 |
32 | {canvas} 33 |
34 | )} 35 | /> 36 | )); 37 | 38 | stories.add('with all controls', () => ( 39 | ( 53 |
54 |
55 | 58 | 59 | 60 | setColor(e.target.value)} /> 61 | 62 | setLineWidth(e.target.value)} 67 | /> 68 | 69 | 74 | 75 | 80 | {imageDownloadUrl ? ( 81 | 82 | Download 83 | 84 | ) : null} 85 |
86 | {canvas} 87 |
88 | )} 89 | /> 90 | )); 91 | 92 | stories.add('with image', () => ( 93 | ( 104 |
105 |
106 | 107 | 110 | {imageDownloadUrl ? ( 111 | 112 | Download 113 | 114 | ) : null} 115 |
116 | 117 | 118 | 119 |
120 | )} 121 | /> 122 | )); 123 | 124 | class WithFileInputDemo extends React.Component { 125 | state = { 126 | image: null 127 | }; 128 | 129 | handleFileInputChange = ev => { 130 | const { target } = ev; 131 | const image = target.files ? target.files[0] : null; 132 | 133 | if (image) { 134 | this.setState({ 135 | image 136 | }); 137 | } else { 138 | console.error('image is null in handleImageSelected'); 139 | } 140 | }; 141 | 142 | render() { 143 | const { width, height, onSave } = this.props; 144 | 145 | return this.state.image ? ( 146 | ( 152 |
153 |
154 | 155 | 156 |
157 | {imageDownloadUrl ? ( 158 | 159 | Download 160 | 161 | ) : null} 162 | 163 | 164 | 165 |
166 | )} 167 | /> 168 | ) : ( 169 | 170 | ); 171 | } 172 | } 173 | 174 | stories.add('with file input', () => ( 175 | 180 | )); 181 | -------------------------------------------------------------------------------- /stories/storybookComponent.jsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | 3 | export const FramedDiv = props => ( 4 |
5 | ); 6 | -------------------------------------------------------------------------------- /test/typescript.tsx: -------------------------------------------------------------------------------- 1 | const library = require('react-testing-library'); 2 | import * as React from 'react'; 3 | import { ReactPainter } from '../src'; 4 | 5 | afterEach(() => { 6 | library.cleanup(); 7 | }); 8 | 9 | test('render empty and save', async () => { 10 | const saveHandler = jest.fn(); 11 | const { getByText, container } = library.renderIntoDocument( 12 | ( 15 |
16 | {canvas} 17 | 18 |
19 | )} 20 | /> 21 | ); 22 | library.Simulate.click(getByText('Save Canvas')); 23 | await library.wait(); 24 | expect(saveHandler).toBeCalled(); 25 | expect(saveHandler.mock.calls.length).toBe(1); 26 | expect(saveHandler.mock.calls[0][0]).toBeInstanceOf(Blob); 27 | }); 28 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "outDir": "dist/", 4 | "sourceMap": true, 5 | "declaration": true, 6 | "noImplicitAny": true, 7 | "module": "commonjs", 8 | "target": "es5", 9 | "jsx": "react", 10 | "lib": ["dom", "es2015"] 11 | }, 12 | "include": ["src/**/*"] 13 | } 14 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": ["tslint:latest", "tslint-react"], 3 | "rules": { 4 | "quotemark": [true, "single", "jsx-double"], 5 | "interface-name": [true, "never-prefix"], 6 | "member-access": false, 7 | "trailing-comma": false, 8 | "semicolon": [true, "always", "ignore-bound-class-methods"], 9 | "arrow-parens": [true, "ban-single-arg-parens"], 10 | "no-console": [true, "log"], 11 | "ordered-imports": false, 12 | "object-literal-sort-keys": false 13 | } 14 | } 15 | --------------------------------------------------------------------------------