SVG drawing in React JS frontend


In this article, we will see how to create an interface on which a user can create drawings, write names, and pretty much any artistic work. You can use this feature to allow users to sign on a page. Here we will use the "react-hooks-svgdrawing" package.

First create a React project −

npx create-react-app tutorialpurpose

Go to the project directory −

cd tutorialpurpose

Example

Install the react-hooks-svgdrawing package −

npm i --save react-hooks-svgdrawing

This library will be used to implement the container which will allow us to make a drawing or anything in the form of SVG using mouse or touchpad.

Add the following lines of code in App.js

import React, { useCallback } from "react";
import { useSvgDrawing } from "react-hooks-svgdrawing";

export default function App() {
   const [renderRef, draw] = useSvgDrawing({
      penWidth: 10, // pen width
      penColor: "#e00", // pen color
      close: false, // Use close command for path. Default is false.
      curve: true, // Use curve command for path. Default is true.
      delay: 60, // Set how many ms to draw points every.
      fill: "none", // Set fill attribute for path. default is `none`
   });
   const handleDownload = useCallback(() => {
      draw.download(); // default svg download
      draw.download({ extension: "svg", filename: "a.svg" });
      draw.download({ extension: "png", filename: "b.png" });
      draw.download({ extension: "jpg", filename: "c.jpg" });
   }, [draw.download]);
   const handleChangeParameter = useCallback(() => {
      // Change pen config draw.changePenColor("#00b");
      // Change pen width draw.changePenWidth(10);
      // Change fill attribure of svg path element. draw.changFill("#00b");
      // Change throttle delay of drawing draw.changeDelay(10);
      // Set whether to use curved comma for svg path element. draw.changCurve(false);
      // Set whether to use curved comma for svg path element. draw.changeClose(true);
   }, [draw]);
   return (
      <div>
      <div
         style={{ width: 500, height: 500, border: "1px solid black" }}
         ref={renderRef} />
         <button onClick={draw.clear}>clear</button>
         <button onClick={draw.undo}>undo</button>
         <button onClick={handleDownload}>download</button>
      </div>
   );
}

Explanation

useSvgDrawing takes two arguments

  • one is a reference, which is assigned to any element to make an area or element drawable, and

  • the second argument is draw, which usually handles every setting like pen width, pen color, downloading the drawing, undo, clear, etc.

Output

Now, let's check the output −

Updated on: 29-Sep-2021

980 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements