1.2.1 • Published 1 year ago

react-drawing v1.2.1

Weekly downloads
4
License
MIT
Repository
github
Last release
1 year ago

react-drawing

React component for drawing on canvas with possibility to pan and zoom from library @sasza/react-panzoom.

"Preview"

Demo

https://codesandbox.io/s/crazy-wildflower-i23nbu - toolbox example

https://codesandbox.io/s/romantic-tesla-oqdmx - above example

https://codesandbox.io/s/strange-cerf-r4txf - example with pan and zoom

https://codesandbox.io/s/quirky-wilbur-ejfjm - example with custom brush color

https://codesandbox.io/s/angry-architecture-ucue3 - example with drawing text

Installation

npm install react-drawing

Usage

Example from GIF above:

import Drawing, { brushFromSrc } from 'react-drawing'

// ...

<Drawing
  brush={brushFromSrc('smile.png',{ width: 30, height: 30 })}
/>

Properties

NameDefaultDescription
brushbrushArcBrush for drawing
height300canvas height in px
fps30drawing interval time
width300canvas width in px
containerWidthwidthwidth of canvas container
containerHeightheightheight of canvas container

Brush

brushArc({ fillStyle = 'black', size = 10 })

Brush on canvas with arc.


brushFromSrc(src, { width, height })

Brush on canvas with specified image. Could be also base64.


brushText({
  fillStyle = 'black', font = 'Arial', text, size = 10,
})

Brush on canvas with text.


brushRect({ fillStyle = 'black', lineWidth = 5, width, height })

Brush on canvas with rect.


brushPanZoom()

Pan and zoom on canvas.

"Preview"


brushCustom({ draw, init })

Brush custom on canvas context:

import Drawing, { brushCustom } from 'react-drawing'

// ...

<Drawing
  brush={brushCustom({
    init: (ctx) => {
      ctx.fillStyle = fillStyle // red
    },
    draw: (ctx, x, y) => {
      ctx.beginPath()
      ctx.moveTo(x,y)
      ctx.lineTo(x + 25,y + 25)
      ctx.lineTo(x + 25, y - 25)
      ctx.fill()
    },
    dependencies: [fillStyle],
  })}
  height={200}
  width={400}
/>

init() method is executed only once, so it's a good place for setting color, line width, stroke-dasharray etc. dependencies[] array to reinit on change.

API

NameDescription
brush(x, y)brush on x, y position of canvas
getCanvas()get canvas node
getContext()get context 2d of canvas
toDataURL()canvas to data URI

Usage:

const ref = useRef()
//...
<Drawing ref={drawingRef} />

Testing

npm run test

Examples

npm run storybook