Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

react-sketch-canvas

vinothpandian63.5kMIT6.2.0TypeScript support: included

react-sketch-canvas - Freehand vector drawing tool for React using SVG as canvas

react-component, sketch, canvas, drawing, freehand, vector, svg-canvas, react-sketch

readme

React Sketch Canvas


Freehand vector drawing component for React using SVG as canvas 🖌



npm    NPM    npm
npm bundle size    npm bundle size
codecov
This project was generated using DTS.

Overview

Features

  • Supports Desktop and Mobile.
  • Accepts input from Mouse, touch, and graphic tablets.

Requirements

  • Requires React >= 16.4

Wanna test React Sketch Canvas before using it?

Installation

If you use npm

npm i react-sketch-canvas

or with yarn

yarn add react-sketch-canvas

Example

Common usage example

import * as React from 'react';
import { ReactSketchCanvas } from 'react-sketch-canvas';

const styles = {
  border: '0.0625rem solid #9c9c9c',
  borderRadius: '0.25rem',
};

const Canvas = () => {
  return (
    <ReactSketchCanvas
      style={styles}
      width="600"
      height="400"
      strokeWidth={4}
      strokeColor="red"
    />
  );
};

To export Data URL of your sketch use ref

import * as React from "react";
import { ReactSketchCanvas } from "react-sketch-canvas";

const styles = {
  border: "0.0625rem solid #9c9c9c",
  borderRadius: "0.25rem"
};

const Canvas = class extends React.Component {
  constructor(props) {
    super(props);

    this.canvas = React.createRef();
  }

  render() {
    return (
      <div>
        <ReactSketchCanvas
          ref={this.canvas}
          strokeWidth={5}
          strokeColor="black"
        />
        <button
          onClick={() => {
            this.canvas.current.
              .exportImage("png")
              .then(data => {
                console.log(data);
              })
              .catch(e => {
                console.log(e);
              });
          }}
        >
          Get Image
        </button>
      </div>
    );
  }
};

List of Props

Props Expected datatype Default value Description
width PropTypes.string 100% canvas width (em/rem/px)
height PropTypes.string 100% canvas width (em/rem/px)
id PropTypes.string "react-sketch-canvas" ID field to uniquely identify a SVG canvas (Supports multiple canvases in a single page)
className PropTypes.string "" Class for using with CSS selectors
strokeColor PropTypes.string black Pen color
canvasColor PropTypes.string white canvas color (HTML colors)
backgroundImage PropTypes.string '' Set SVG background with image URL
exportWithBackgroundImage PropTypes.bool false Keep background image on image/SVG export (on false, canvasColor will be set as background)
preserveBackgroundImageAspectRatio PropTypes.string none Set aspect ratio of the background image. For possible values check MDN docs
strokeWidth PropTypes.number 4 Pen stroke size
eraserWidth PropTypes.number 8 Erase size
allowOnlyPointerType PropTypes.string all allow pointer type ("all"/"mouse"/"pen"/"touch")
onChange PropTypes.func | Returns the current sketch path in CanvasPath type on every path change
onStroke PropTypes.func | Returns the the last stroke path and whether it is an eraser stroke on every pointer up event
style PropTypes.object false Add CSS styling as CSS-in-JS object
svgStyle PropTypes.object {} Add CSS styling as CSS-in-JS object for the SVG
withTimestamp PropTypes.bool false Add timestamp to individual strokes for measuring sketching time

Set SVG background using CSS background value

You can specify width and height values in em or rem. It fills the parent element space if width and height are not set


Methods

You can export the sketch as an image or as a svg

Use ref to access the element and call the following functions to export image

Props Expected datatype
eraseMode(boolean) Switch to eraser mode by passing true. You can switch back to pen mode by passing false
clearCanvas() Clears the canvas.
resetCanvas() Resets the canvas and clears the undo/redo stack along with it.
undo() Undo the last action.
redo() Redo the previous action.
exportImage(imageTypeString) Accepts an image type as argument (ExportImageType) and returns a Promise which resolves to base64 data url of the sketch.
exportSvg() returns a Promise which resolves to an inline SVG element.
exportPaths() returns a Promise which resolves to an instance of CanvasPath.
loadPaths(CanvasPath) Accepts an CanvasPath exported from exportPaths() and loads it on the canvas.
getSketchingTime() returns a Promise which resolves the time that user sketched in the canvas (considers only when the user made the strokes or erased the strokes)

Types

type ExportImageType = 'jpeg' | 'png';

interface Point {
  x: number;
  y: number;
}

interface CanvasPath {
  paths: Point[];
  strokeWidth: number;
  strokeColor: string;
  drawMode: boolean;
  startTimestamp?: number;
  endTimestamp?: number;
}

Thanks to

  • Philipp Spiess' tutorial
  • Draws smooth curves, thanks to François Romain's tutorial

changelog

Changelog

[6.1.0]

Added

  • Added optional id props to uniquely identify a sketch canvas
  • Upgraded dependencies

Changed

  • Updated tests to use the id props

Fixed

  • Fix multiple ReactSketchCanvas in one page causes issues due to id="background" #52
  • Fix ReactSketchCanvas doesn't work on safari. #53

[6.0.3]

Fixed

  • Fix Package cannot be installed via npm #51
  • update contributing.md
  • update github actions

[6.0.2]

Added

  • Added cypress tests for all props and events
  • Added onStroke prop to get last stroke on pointer up
  • Adds a point on click (without moving) #45

Changed

  • Upgraded all dependencies
  • Moved to DTS (tsdx fork) instead of nx
  • Switched codebase to hook based implementation (support react >= 16.8)
  • Removed immer dependency

Fixed

  • Changed React import to * from React #40
  • Export image fails when the background is not an image [beta] #46
  • Fix partial transparent erase (eraser stroke color changed to black for masking, add maskUnits) #44

Breaking changes

  • Renamed onUpdate to onChange

[6.0.1-beta]

Added

  • Upgraded all dependencies
  • Updated directory structure
  • Added background image rendering directly in SVG
  • Added option to export background image while exporting the canvas as image or SVG
  • Added background image aspect ratio control
  • Updated erase option to use mask instead of canvas color
  • Add github action for deployment of storybook and package

Breaking changes

  • Removed background option to set background image using CSS-in-JS (instead check feature-filled backgroundImage prop)

[5.3.5]

Changed

  • Changed import react as import * as React from 'react'

[5.3.4]

Added

  • Switched to Nx
  • Updated documentation

Changed

  • Removed pepjs. Can be polyfilled by the web app directly instead

[5.3.3]

Fixed

  • add support any version above react 16.4

[5.3.2]

Fixed

  • Bump dependency versions

[5.3.1]

Fixed

  • Set default value of allowOnlyPointerType as 'all' again

[5.3.0]

Added

  • Reset canvas option to reset internal state and clean undo/redo stack

Fixed

  • Fix exportImage function to export png in Firefox and Safari

[5.2.0]

Added

  • Add withTimestamp prop and getSketchingTime function to measure the sketching time of the user

[5.1.2] & [5.1.1] (Both are same - Sorry)

Added

  • Add index.d.ts to npm registry
  • Add Github as registry
  • Update example

[5.1.0]

Added

  • Added defaultProps to onUpdate in ReactSketchCanvas
  • Added touch-action="none" to allow pepjs polyfill pointer events
  • Update README.md

Fixed

  • Removed the annoying console.log from Canvas

[5.0.1]

Added

Added README :)

[5.0.0]

Added

  • Rewrote codebase in typescript
  • Added pepjs to support more browsers
  • Added onUpdate feature to get current paths in CanvasPath type

Fixed

  • Fixed sketch offset issue when the canvas is scrolled

Changed

  • Updated undo/redo/reset strategy
  • Updated demo in storybook

[4.0.0]

Added

  • Renamed SvgSketchCanvas to ReactSketchCanvas to keep naming convention
  • Added className property to set class names for CSS selectors

Deprecated

  • Removed SvgSketchCanvas

[3.0.1]

Changed

  • Moved immutable dependency from Canvas file

[3.0.0]

Changed

Removed onUpdate feature and made the system modular

Added

  • Made Canvas as a separate module. Now event handlers can be hooked with Canvas class to update paths from server. (For Collaboration use case)

Deprecated

  • Removed onUpdate feature and instead made Canvas module

[2.3.0]

Added

  • Added onUpdate property to get the current sketch paths after every update

[2.2.0]

allowOnlyPointerType

Added

  • Added "allowOnlyPointerType" use-case. Now single pointer type can be targetted

[2.1.0]

Added

  • Switched to pointer events

[2.0.1]

Added

  • Add SVG background using CSS

[2.0.0]

Added

  • Export and load paths
  • Erase mode and eraser width

Changed

  • Rename exportAsImage() to exportImage() for naming consistency

Deprecated

  • Rename exportAsImage()