GithubHelp home page GithubHelp logo

vinothpandian / react-sketch-canvas Goto Github PK

View Code? Open in Web Editor NEW
367.0 6.0 67.0 6.55 MB

Freehand vector drawing component for React using SVG as canvas 🖌️

Home Page: https://vinoth.info/react-sketch-canvas

License: MIT License

JavaScript 2.00% TypeScript 94.17% HTML 0.20% CSS 0.40% MDX 3.24%
canvas react sketch component freehand-drawing sketching react-library

react-sketch-canvas's Introduction

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 built using Turborepo.

Overview

Features

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

Requirements

  • Requires React >= 16.8

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
readOnly PropTypes.bool false Disable drawing on the canvas (undo/redo, clear & reset will still work.)

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

react-sketch-canvas's People

Contributors

daanda97 avatar dependabot[bot] avatar jjherscheid avatar kastango avatar leerobert avatar nhnt11 avatar rickythink avatar vinothpandian avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

react-sketch-canvas's Issues

Feature to block the user of drawing at the canvas

I would like to know if there is already a feature that does not allow the user to draw on the canvas. For example, a canDraw property at ReactSketchCanvas that avoids the user to draw on it?

I'm developing a drawing game and I want to only allow the user to draw when it's his turn. I already kinda implemented it while I was checking the code, if this feature does not exist, I can add it.

Add resizable canvas option

The withViewBox property works to scale everything up/down on resize. but then when you add another stroke to the canvas after resizing, all strokes on the canvas "shift" and I encounter the same problem where the strokes all get cut off

Originally posted by @dereklance in #116 (reply in thread)

loadPaths() is laggy for data coming in from onUpdate() via socket-io (Collaborative canvas)

Describe the bug
Hello. Awesome work on the canvas!!
I am trying to sync two whiteboards with each other. But the two keep getting laggy till it's barely usable

To Reproduce
When something is drawn on the first whiteboard, I get the CanvasPath[ ] from onUpdate() and send to the second whiteboard via socketio.
On the second whiteboard, socketio captures the sent CanvasPath[ ] and I use loadPath() to display it on the screen.
It works okay for the first few seconds and what is drawn on one end reflects quickly on the other.
Then gets keeps getting laggy to the point where there is a huge delay. There is even a lag when drawing on the original whiteboard, leave alone reflecting on the other one.
I also noticed that loadPaths() was trigerring onUpdate(), so I disabled socketio sending the paths until data is loaded

Expected behavior
loadPaths() should not cause a lag

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: Kubuntu 20.04
  • Browser : Chrome
  • Version 86.0.4240.183

My code
`
import React,{ useState, useEffect } from "react";
import { ReactSketchCanvas } from "react-sketch-canvas";
import ReactTooltip from 'react-tooltip';
import { getsocketIoInstance } from '../utils/socketio-client';

export default class Whiteboard extends React.Component {
constructor(props) {
super(props);
this.styles = {
border: "0.0625rem solid #9c9c9c",
borderRadius: "0.25rem",
};
this.canvas = React.createRef();
this.state = {
eraseMode: false
}
this.pauseSync = false;
this.WhiteBoardMsgType = {
canvas_draw: 1,
canvas_undo: 2,
canvas_redo: 3,
canvas_clear: 4,
}
this.roomName = sessionStorage.getItem('roomName');
this.socketIo = getsocketIoInstance(this.roomName, 'Whiteboard');
}

componentDidMount() {
this.socketIo.on('whiteboard', (changes) => {
const { type, drawUpdates } = changes;
if (type === this.WhiteBoardMsgType.canvas_draw) {
this.pauseSync = true;
this.canvas.current.loadPaths(drawUpdates);
this.pauseSync = false;
// setTimeout(() => {
// this.pauseSync = false;
// }, 50);
}
});
}

whiteBoardUpdated = (drawUpdates) => {
if (!this.pauseSync) {
const changes = { roomName: this.roomName, type: this.WhiteBoardMsgType.canvas_draw, drawUpdates }
this.socketIo.emit('whiteboard', changes);
}
// console.log('pause sync', this.pauseSync);
}
toggleEraseMode = () => {
this.canvas.current.eraseMode(!this.state.eraseMode);
this.setState({ eraseMode: !this.state.eraseMode })
}
undoCanvas = () => {
this.canvas.current.undo();
// no need to send this change as they are already captured in the drawUpdates
// const changes = { roomName: this.roomName, type: this.WhiteBoardMsgType.canvas_undo }
// this.socketIo.emit('whiteboard', changes);
}
redoCanvas = () => {
this.canvas.current.redo();
// no need to send this change as they are already captured in the drawUpdates
// const changes = { roomName: this.roomName, type: this.WhiteBoardMsgType.canvas_redo }
// this.socketIo.emit('whiteboard', changes);
}
clearCanvas = () => {
this.canvas.current.clearCanvas();
// no need to send this change as they are already captured in the drawUpdates
// const changes = { roomName: this.roomName, type: this.WhiteBoardMsgType.canvas_clear }
// this.socketIo.emit('whiteboard', changes);
}

render() {
return (


Whiteboard






<i className="fas fa-eraser" data-tip={this.state.eraseMode ? 'Stop Erase': 'Erase'}
onClick={this.toggleEraseMode}>
<i className="fas fa-broom"data-tip='Clear' onClick={this.clearCanvas}>

<ReactSketchCanvas
ref={this.canvas}
style={this.styles}
// width="600"
// height="400"
strokeWidth={4}
strokeColor="red"
eraserWidth={20}
onUpdate={this.whiteBoardUpdated}
/>

);

}
}
`

partial changes in strokes after transparent erase

Thanks for your excellent work! I have used the version 6.0.1 and it is very helpful.
I found a little issue during using it. So I hope you can kindly give me some help for it.

Describe the bug
When using transparent erase, the former color brush stroke will change partially. It is very strange that if I draw a few more strokes (4 strokes or more) before using the eraser, the issue disappears.
This issue may be related to #39 .

Desktop:

  • OS: macOS
  • Browser: chrome

Screenshots

test2.mp4

Resize the canvas content based on the device screen / container width

If I draw something on the canvas from a desktop device, when I upload the path on a mobile react-sketch-canvas, it cuts out a part of the drawing, showing only the top left corner of the content.

Canvas drawing from desktop:
image

Canvas Drawing from Mobile:
image

I'm currently working with Ionic-React/Typescript.

Is there a way to keep the content visible when changing the canvas width and height?

Thank you in advance!

Question: callback similar to onUpdate that is not triggered everytime

Describe the bug
Is there a callback function that is triggered when the user is done drawing on the canvas.

To Reproduce
Steps to reproduce the behavior:
onUpdate callback function is triggered everytime

Expected behavior
a callback that is triggered when the user is done drawing the path

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: [e.g. iOS]
  • Browser [e.g. chrome, safari]
  • Version [e.g. 22]

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

Uncaught error

When i submit i got this error

Error:
canvas {current: ReactSketchCanvas}current: null[[Prototype]]: Object
Uncaught (in promise)

obtain a brush segment

Thank you for your great work, this package is really helpful!
I noticed the onUpdate is triggered very frequently when the mouse is brushing. Is there a way to just get a segment of brush between the user's click-and-release of the mouse?
Thank you very much!

Is there a way to rotate the canvas?

Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

I am using the module to annotate images by setting the image as the background and canvas as a layer on top of the image. Now when I am trying to rotate the canvas, the background image is rotated but the pen behaves weird by moving in different directions.

Can we please have an option for a rotating background?

Here is the small video snippet I created for a better understanding:-
https://www.loom.com/share/28effbb145bf4fd88af7bc4f2bc60d52

Multiple ReactSketchCanvas in one page causes issues due to id="background"

I wrapped ReactSketchCanvas to form a new component and used it multiple times in one page. I passed different imageSrc props and assigns it to backgroundImage={props?.imageSrc}.

v5.3.3 - works

v6.0.3 - doesn't work.

//DrawingComponent.js
function DrawingComponent(props) {
     ... 

     return (
                  <ReactSketchCanvas
                        ref={drawing}
                        style={styles}
                        width={'auto'}
                        height={512}
                        strokeWidth={1}
                        strokeColor={state.color}
                        backgroundImage={props?.imageSrc}
                    />
     )
}

//Usage
//Home.js

<DrawingComponent
    imageSrc={'image_path_1'}
    ...other props
/>

<DrawingComponent
    imageSrc={'image_path_2'}
    ...other props
/>

<DrawingComponent
    imageSrc={'image_path_3'}
    ...other props
/>

All 3 sketch canvas is displaying "image_path_1". Inspected the image and I noticed that it uses id="background" for all the canvas. Is this a bug? or there's some configuration that I missed?

Thank you.

`exportWithBackgroundImage` does not work when background image is set using datauri

Describe the bug
First of all, this project is awesome. However, what is preventing me from using it, is that there is a bug when adding a backgroundImage from a dataURI, and then attempting to export the image without the background image

To Reproduce
To reproduce

  1. Go to the demo
  2. Add a background image from a dataURI (Can be anything)
  3. Add some strokes
  4. Uncheck exportWithBackgroundImage
  5. Export Image

Expected behavior
Image is exported without the background image.

Actual behavior
Image is exported with the background image. Note: The SVG is exported correctly, without the background image.

Screenshots
Screen Shot 2022-12-29 at 4 35 06 PM

Desktop (please complete the following information):

  • OS: Mac OS
  • Browser: Chrome

Testing with jest/vitest

This is not really a bug but rather a stumping behaviour.
I need to write unit tests for a component that uses this library.
I want to test that my callback is actually being called with the edited image.
My test in vitest is:

    function renderImageEditor({ open = true, useEdited = false }: { open?: boolean, useEdited?: boolean } = {}) {
      const mockOnClose = vi.fn();
      const mockOnEdit = vi.fn();
      const mockOriginalImage = 'original';
      const mockEditedImage = 'edited';
      const getters = render(
        <ImageEditor
          open={open}
          originalImage={mockOriginalImage}
          editedImage={useEdited ? mockEditedImage : undefined}
          onClose={mockOnClose}
          onEdit={mockOnEdit}
        />,
      );
      return {
        ...getters, mockOnEdit, mockOnClose, mockOriginalImage, mockEditedImage,
      };
    }

    it('should submit new image when saving after editing', () => {
      const {
        getByTestId, mockOnEdit, mockEditedImage, mockOriginalImage,
      } = renderImageEditor({ useEdited: true });
      const canvas = document.getElementById(imageEditorTestIds.canvas)!;
      fireEvent.mouseDown(canvas);
      fireEvent.mouseMove(canvas);
      fireEvent.mouseUp(canvas);
      const button = getByTestId(imageEditorTestIds.submit);
      fireEvent.click(button);
      expect(mockOnEdit).toHaveBeenCalled();
      expect(mockOnEdit).not.toHaveBeenCalledWith(mockEditedImage);
      expect(mockOnEdit).not.toHaveBeenCalledWith(mockOriginalImage);
    });
  });

I'm using id because using data-testid doesn't actually reach the underlying element.
This test fails, claiming that my function is not being called at all.

For brevity, here is my minimal component:

function Component = ({onEdit, originalImage, editedImage}) => {
  const [isEdited, setIsEdited] = useState<boolean>(false);
  const canvasRef = useRef<ReactSketchCanvasRef>(null);

  const onSubmit = async () => {
    if (isEdited) {
      const data = await canvasRef.current?.exportImage('jpeg');
      onEdit(data || originalImage);
      onClose();
    }
  };


  return <div data-testid={testIds.wrapper}>
           <ReactSketchCanvas
        id={testIds.canvas}
        ref={canvasRef}
        backgroundImage={editedImage || originalImage}
        className='w-full h-full'
        strokeWidth={4}
        strokeColor='red'
        exportWithBackgroundImage
        onStroke={() => setIsEdited(true)}
      />
    </div>

If onEdit is not being called, it means the isEdited is not being changed to true, which means my test never triggers the onStroke.
How do I actually test this?

coverage data in dist folder files of npm package interfering with jest coverage

Describe the bug
Coverage data are found in various files in dist folder of the npm package, causing increased file size and more importantly interfering with jest coverage data (running jest with coverage reports extra info from this pacakge).

To Reproduce
Steps to reproduce the behavior:

  1. Go to https://unpkg.com/[email protected]/dist/react-sketch-canvas.cjs.development.js and check the file content
  2. Go to https://unpkg.com/[email protected]/dist/react-sketch-canvas.esm.js and check the file content
  3. Go to https://unpkg.com/[email protected]/dist/react-sketch-canvas.cjs.production.min.js and check the file content

Observe the following:

function cov_20wqqco38b() {
  var path = "/home/vinoth/projects/react-sketch-canvas/src/Paths/index.tsx";
  var hash = "80c4a162af9ff11419db7b7c460ec352bdae34fe";
  var global = new Function("return this")();
  var gcv = "__coverage__";
  var coverageData = {
    path: "/home/vinoth/projects/react-sketch-canvas/src/Paths/index.tsx",
    statementMap: {
      "0": {
        start: {
          line: 5,
          column: 23
        },
        end: {
          line: 13,
          column: 1
        }
      },
      "1": {
        start: {
          line: 6,
          column: 4
        },
        end: {
          line: 10,
          column: 5
        }
      },
      "2": {
        start: {
          line: 7,
          column: 25
        },
        end: {
          line: 7,
          column: 33
...

Expected behavior
no coverage data inside

Screenshots
file content:
Screenshot 2022-02-04 at 10 08 28 PM

production min file:
Screenshot 2022-02-04 at 10 16 06 PM

interference with jest:
Screenshot 2022-02-04 at 10 11 13 PM

Desktop (please complete the following information):

Smartphone (please complete the following information):

Additional context

Canvas vertical stroke not working in line web browser

20230608_003713.mp4

Description
The vertical strokes in the canvas are not working in the line web browser for iPhones.

To Reproduce
Steps to reproduce the behavior:

  1. Go to the Line application
  2. Paste the URL where the canvas is deployed
  3. Click on the URL
  4. The link will be opening in the line web browser
  5. Draw vertical strokes on the canvas.

Expected behavior
Vertical strokes should be drawn properly and precisely.

Actual behavior
The screen is moving instead of displaying the strokes. Only dots or small lines can be done on the canvas.

Smartphone:

  • iPhones all versions

Attaching a video for better understanding
https://github.com/vinothpandian/react-sketch-canvas/assets/53820526/5709f30a-4a56-482b-b42e-8aa8a4b28699

No-renders-for-reactapp

I ran the installation and implementation as shown in the underlying docs, though i wasnt able to run it, my react app port 3000 just freezes the moment i add ReactSketchCanvas

Installation Issue

Describe the bug
React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object.

To Reproduce
Steps to reproduce the behavior:

  1. npm i react-sketch-canvas
  2. import ReactSketchCanvas from "react-sketch-canvas";
  3. Canvas render
  4. See error

Expected behavior
I have followed the installation steps and I have had errors in the component rendering.

Screenshots
Attached screenshots of console errors
image
image
image

Desktop (please complete the following information):

  • OS: Windows 10
  • Browser Chrome
  • Version 85

I appreciate your help

inaccurate first brush and unrecoverable erase brush

Describe the bug
Thanks for the v6 release with optional background image export and better erase brush! That is awesome!

I have updated the package and tried it, and found there are two minor issues (maybe not considered as bugs). Thus I hope to let you know here, and see if you could kindly provide some help.

  1. The first brush is inaccurate when it's drawn, but will become normal after the second brush. This is strange and not sure whether you could reproduce the same issue.
  2. The transparent erase function is great, but when some color brush is re-drawn on the erased area, the transparency cannot be overwritten.

To Reproduce
Directly use the component.

Screenshots

Screen.Recording.2021-08-25.at.10.33.40.AM.mov

Desktop (please complete the following information):

  • OS: MacOS
  • Browser: chrome

Export Image doesn't export background

Describe the bug
When use exportImage it exports to base64 without the background image that was added to canvas.

To Reproduce
Steps to reproduce the behavior:

  1. add background image in canvas.
  2. Draw on canvas with a bgimage
  3. exportImage jpeg
  4. img tag will only have strokes without background of canvas

Expected behavior
it should contain background image with strokes on it in base64 url.

Screenshots
If applicable, add screenshots to help explain your problem.

Smartphone (please complete the following information):

  • Device: Laptop
  • OS: Ubuntu
  • Browser: Chrome

Optimize data structure and code while keeping backward compatibility

The current implementation has to split eraser and pen strokes during render. This is reducing the performance (obviously) of the component.

  • Update CanvasPath to have both eraser and pen strokes separately (Reduce time complexity)
  • Update undo/redo to action based instead of replicating data (Reduce space complexity)
  • Keep backward compatibility by adding a split method in loadPaths

pan and zoom

i want to use this pad for filling forms, i need it have zoom feature to be friendly.

slow performance

Hi.
after about a few lines of hand writing in android device, it becomes slow and laggy. Is there any solution to use this great library to write for example a full a4 page in android tablets? I used react memo, but there was no difference.
thanks
import * as React from "react";
import { ReactSketchCanvas } from "react-sketch-canvas";
const width = window.innerWidth
const height = window.innerHeight
const styles = {
border: "0.0625rem solid #9c9c9c",
borderRadius: "0.25rem",
width: width,
height: height/4,
backgroundColor: "#343434"
};

export const DrawinCanvas2 = () => {
return (

);
};`

v6.0.3 doesn't work on safari.

Describe the bug
Doesn't work on safari after upgrading it to v6.0.3.

v5.3.4 - works
v6.0.3 - doesn't work

To Reproduce
Update the project and run on safari browser.

Screenshots

Screenshot 2021-10-27 at 6 25 40 PM

[Chrome and Safari for iPad] - Export base64 with exportImage only shows the top 30% of the stokes

Describe the bug
I was testing drawing something on Chrome for iPad and saw this.
After drawing a stroke, export as "png" with exportImage. The Base64 image only shows the top 30% of the strokes, but a vertical line that covers all of the canvas was draw. This is happening on the playground and in my personal project.

To Reproduce
1_ Open Chrome or Safari on iPad
2_ Go to https://vinoth.info/react-sketch-canvas/?path=/story/full-demo--sketch-canvas
3_ Draw something vertically across the canvas
4_ export as image (exportImage)

Expected behavior
Should see the entire stroke

Actual behavior
Only the top 30% of the stroke is visible

Screenshots

Smartphone (please complete the following information):

  • Device: iPad 5th generation
  • OS: iOS 14
  • Browser: Safari and Chrome
  • Version [e.g. 22]

Select mode feature

I'd like to suggest for select mode, so you can select specific draw and drag around or copy paste it. Maybe it can come along with basic shape feature like rectangle or circle etc. I'm not really good with canvas, so it'll be really helpful.

Thank You

TypeScript types are missing from dist folder!

Describe the bug
Types (index.d.ts) is missing from dist folder on latest release

To Reproduce
Steps to reproduce the behavior:

  1. Run npm i react-sketch-canvas to install on a TS project
  2. Run it, it will complain that types are not being found

resizing canvas resizes background image but not paths

Describe the bug

if a ReactSketchCanvas loads a background image and has some hand-drawn paths on it, if the canvas is resized, the background image will resize correctly, while the drawn paths will appear in an "incorrect" location as they are not resized

To Reproduce
bug demo:

  1. go to https://vinoth.info/react-sketch-canvas/
    the conditions for the bug are met -- the canvas size is 100% (i.e. it's not a fixed pixel amount) and has a background image
  2. draw some paths by hand
  3. resize the window -- make it smaller for example

the background image will correctly resize, while the paths will remain in their (now) incorrect positions as they are not resized

Expected behavior

when resizing the canvas, both the background image and the drawn paths should resize together to stay in "sync"

Screenshots

before resize:

image

after horizontal resize:

image

Desktop (please complete the following information):

  • OS: macOS 12.4
  • Browser: Chrome
  • Version: 107.0.5304.110

Make canvas transparent?

I would like to overlay the canvas over a three.js 3D scene and allow users to draw on the 3D scene. Currently I'm setting the zIndex to overlay the canvas, but its default color is white so its opaque and blocks the three.js scene.

Would be great to set the canvas to be transparent

Base64 String Image in background is distorted

Describe the bug
When we provide a base64 encoded string of an image to the prop backgroundImage, the background image is not showing up properly, it is distorted and with very small height(not filling the canvas and not recognizable)

To Reproduce

                            <ReactSketchCanvas
                                ref={ canvasRef }
                                style={{
                                    border: '0.0625rem solid #9c9c9c',
                                    borderRadius: '0.25rem'
                                }}
                                height={ naturalHeight }
                                width={ naturalWidth }
                                strokeWidth={ 4 }
                                strokeColor="red"
                                backgroundImage={ base64String }
                                exportWithBackgroundImage
                            />

Expected behavior
The background image should be displayed in the canvas with the height and width of the actual image

Desktop (please complete the following information):

  • OS: iOS
  • Browser : Chrome
  • Version : 96.0.4664.110 (Official Build) (x86_64)

Additional context
When the sketched image is downloaded, it is getting downloaded correctly.

Bump immer version to at least 8.0.1

Describe the bug
A Prototype Pollution vulnerability affecting immer version 7.0.9 has been raised by Snyk when trying to npm install react-sketch-canvas.

Expected behavior
Would be nice to update the immer dependency version to at least 8.0.1 or the latest version 9.0.1.

Thanks.

Bug when exporting with background image

Describe the bug
If you export the background image the background picture will not scale correctly.

To Reproduce
Steps to reproduce the behavior:

  1. Go to https://vinoth.info/react-sketch-canvas/

  2. Use any image url for the background image (for example: https://upload.wikimedia.org/wikipedia/en/d/d4/Mickey_Mouse.png)

  3. click export image

  4. Background image is not exported with correct scale shown on canvas
    image

  5. Set xMinYMin for preserveBackgroundImageAspectRatio

  6. click export image

  7. Background image is broken
    image

Expected behavior
Image should export like so when not using preserve background image ratio
image

Image should export like so when using xMinYmin
image

Desktop (please complete the following information):

  • Windows
  • Chrome

onFinish drawing

It would be very useful if we have a callback on finish drawing, this can be triggered when the mouse up event happens

When the user finishes drawing, an event should fire

An alternate solution is to have debounce in the current update, but an event that is fired on finish of drawing will be very useful

Getting some vector glitches when drawing

Describe the bug
Getting some vector glitches when drawing (see the image below)

Screenshots
bugs

Desktop (please complete the following information):

  • OS: Windows
  • Browser: Google Chrome
  • Version: 114.0.5735.199

onUpdate doesn't seem to trigger

Describe the bug
onUpdate method doesn't seem to trigger

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: [e.g. iOS]
  • Browser [e.g. chrome, safari]
  • Version [e.g. 22]

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

[Bug] A blank white space appears when erasing the canvas

Describe the bug
A blank white space appears and covers the middle to the bottom section of the canvas when erasing the canvas.
Here is the video https://www.awesomescreenshot.com/video/13450607?key=caaf718794e5b4e01723f8472a025b6d

To Reproduce
Steps to reproduce the behavior https://www.awesomescreenshot.com/video/13449258?key=45a625eae8aa43585ed4d2f5a3f89d72:

  1. Open this codesandbox https://codesandbox.io/s/forked-learn-react-sketch-canvas-r7xphg?file=/src/Demo.jsx
  2. Create some scratches to the canvas (using the default/initial conditions).
  3. Change the color of the scratch by clicking the "Select Color" button.
  4. Create some scratches to the canvas again.
  5. Change the stroke type/width from regular to bold by clicking the "Select Stroke" button.
  6. Create some scratches to the canvas again.
  7. Change the stroke type from bold to the eraser.
  8. Create some scratches using the eraser on the canvas.
  9. Sometimes the bug (blank white space) appears here. If not, please continue trying by repeating the steps above again.

Expected behavior
No blank white space appears.

Screenshots
(Attached above).

Desktop:

  • OS: tested on Windows 11 and macOS Monterey 12.4
  • Browser: both OS are tested on Chrome 108 also Edge on Windows

Smartphone (please complete the following information):

  • Device: not tested yet
  • OS: not tested yet
  • Browser not tested yet

Additional context
If we export the canvas to an image file (by clicking the "Save" button), the exported image has no blank white space inside it.
image

In the codesandbox above, I have copied and pasted your code from the example folder to the App component but I didn't find any issue.
image

Canvas path edges are not smooth when drawn using pencil

Describe the bug
When we draw or write something on the canvas using an apple pencil the paths are not crisp.
Whereas on the web its fine.
Image attached here
Screenshot 2020-04-29 at 10 55 30 PM

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
Things drawn or written on the canvas should be crisp.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: ipadOS 13
  • Browser - chrome for ipad

Additional context
Add any other context about the problem here.

How to store data in state in canvas?

I am using your npm package [react-sketch-canvas] for the doctor to write prescription in scratch pad.
How to do storing for canvas in state so that doctor can come back to the scratch pad and write on top of the existing??

erase mode overlaying white color on the background

Is your feature request related to a problem? Please describe.
As the following image shows, the current eraseMode is overlaying white color on the background image, which in my opinion should not be the real "erase". Could it be possible to make the svg just empty on that region when doing erase?
image

Describe the solution you'd like
The while color region in the above image should be recovered and display the background.

Describe alternatives you've considered
Not yet

Additional context
N.A.

Not sure whether this makes sense, please advise! Thank you in advance!

Eraser not working with darkreader

Describe the bug
when using the super-popular darkreader addon, the eraser is not working.

To Reproduce
Steps to reproduce the behavior:

  1. Install and activate darkreader addon
  2. draw some lines on canvas
  3. try to erase it

Expected behavior
the "erased" area should be hidden

Actual behavior
the drawn line becomes transparent, and it is visible only where it was "erased".

Screenshots
before
image
after "erasing" the letter "P"
image

Desktop:

  • Browser Chrome, Edge
  • Version 112

Firefox compatibility

Describe the bug
Thanks for the new version release! I had an issue when using it on Firefox. It seems that the current version is not very compatible with Firefox, brush strokes are not displayed properly.

To Reproduce
Run on Firefox browser, and draw.

Desktop (please complete the following information):

  • OS: MacOS
  • Browser: Firefox

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.