Obtain a masterpiece by creating a canvas in React

Greetings! I have developed a drawing app using react and I am looking for a way to capture what the user has drawn on the canvas when they release the mouse button. This process should repeat continuously until the user stops drawing. Can anyone suggest how I can achieve this? Thank you in advance for your assistance!

import { useEffect, useRef, useState } from "react";
import Menu from "./Menu";
import "./App.css";
import { useStateContext } from '../../contexts/ContextProvider';

const DrawingSEC = () => {

    const canvasRef = useRef(null);
    const ctxRef = useRef(null);
    const [isDrawing, setIsDrawing] = useState(false);
    const [lineWidth, setLineWidth] = useState(2);
    const [lineColor, setLineColor] = useState("black");
    const { screenSize, setScreenSize } = useStateContext();
  
    useEffect(() => {
      const handleResize = () => setScreenSize(window.innerWidth);
      window.addEventListener('resize', handleResize);
  
      handleResize();
      return () => window.removeEventListener('resize', handleResize);
    });
    
    // Initialization when the component
    // mounts for the first time
    useEffect(() => {
      const canvas = canvasRef.current;
      const ctx = canvas.getContext("2d");
      ctx.lineCap = "round";
      ctx.lineJoin = "round";
      ctx.strokeStyle = lineColor;
      ctx.lineWidth = lineWidth;
      ctxRef.current = ctx;
    }, [lineColor,  lineWidth]);
    
    // Function for starting the drawing
    const startDrawing = (e) => {
      ctxRef.current.beginPath();
      ctxRef.current.moveTo(e.nativeEvent.offsetX, e.nativeEvent.offsetY);
      setIsDrawing(true);
    };
    
    // Function for ending the drawing
    const endDrawing = () => {
      ctxRef.current.closePath();
      
      setIsDrawing(false);
    };
    
    const draw = (e) => {
      if (!isDrawing) {
        return;
      }
      ctxRef.current.lineTo(e.nativeEvent.offsetX, e.nativeEvent.offsetY);
        
      ctxRef.current.stroke();
    };
  return (
    <div className="App">
      <div className="draw-area">
        <Menu
          setLineColor={setLineColor}
          setLineWidth={setLineWidth}
          lineWidth={lineWidth}

        />
        <canvas
          onMouseDown={startDrawing}
          onMouseUp={endDrawing}
          onMouseMove={draw}
          ref={canvasRef}
          width={screenSize-300}
          height={`720px`}
        />
      </div>
    </div>
  )
}

export default DrawingSEC

Menu Section :

import React from "react";
import "./App.css";

const Menu = ({ setLineColor, setLineWidth,lineWidth }) => {
return (
    <div className="Menu">
    <label>color  </label>
    <input
        type="color"
        onChange={(e) => {
        setLineColor(e.target.value);
        }}
        style={{borderRadius: "50%"}}
    />
    <label>linewidth </label>
    <input
        type="range"
        min="3"
        max="20"
        value={lineWidth}
        onChange={(e) => {
        setLineWidth(e.target.value);
        }}
    />
    
    </div>
);
};

export default Menu;

App.css:

@import url("https://fonts.googleapis.com/css2?family=Lobster&display=swap");

.App {
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
  background-image: linear-gradient(120deg, #fdfbfb 0%, #ebedee 100%);
}

h1 {
  font-family: "Lobster", cursive;
  font-size: 50px;
  color: #4644f0;
}

.draw-area {
  height: 720px;
  border: 2px solid #808080;
  position: relative;
  background-color: white;
}
.draw-area canvas {
  
}

.Menu {
  width: 650px;
  height: 50px;
  display: flex;
  justify-content: space-evenly;
  border-radius: 5px;
  align-items: center;
  background-color: #a3a3a32d;
  margin: auto;
  margin-top: 10px;
 
}

I would like the canvas to be converted into an image and sent somewhere whenever the user releases the mouse button on the canvas.

Answer №1

It is recommended that you include the following line in your endDrawing function:

      console.log(canvasRef.current.toDataURL());


By doing this, a link will be displayed in the console allowing you to save it into another variable.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to input information into Textbox in real-time

Having trouble entering data from one page to another using ng-model. After filling in some information in a textbox and moving to the next page, I want the same data to be entered when I return to the previous page. I've written the code but it doesn ...

Tips for creating the X Mark using SVG and CSS

I'm struggling to create an animation of an "X" checkmark sign (for failure). Although I found a great example of an animated checkmark sign for success, the code uses a curve-bezier design that I can't replicate for the "X" sign. If anyone cou ...

What is the best way to determine which id has been clicked using jQuery?

Can someone help me figure out how to determine which button has been clicked using jQuery? Here is the HTML code I am working with: <div class="row"> <div class="col-md-6"> <div class="well " id="option_a"> </div& ...

How can you retrieve the preceding sibling using an Angular directive?

Currently, I am utilizing ELEMENTREF to interact with the DOM via Renderer2. Allow me to provide a simple example: import { Directive, Renderer2, ElementRef } from '@angular/core'; @Directive({ selector: '[appHighlight]' }) export c ...

Tips for handling undefined values in observable next methods to return a default error message

I sent a request over the network and received a response. Whenever I encounter an undefined value in the response, I want to return a default error message. The response may contain multiple levels of nested objects. Is there a way to replace the if else ...

Using CSS3 easing on Mobile Safari can help create smooth transitions

Can anyone advise on how to recreate the easing/friction for touch events in Mobile Safari? I am trying to achieve a similar bounce-back effect when dragging contents past the top or bottom of a scroller. I experimented with the cubic-bezier easing functi ...

Building a date conversion process using JavaScript

Is there a way to change this date format: Sun Jan 08 2012 00:00:00 GMT+0530 (Sri Lanka Standard Time) to look like this: 2012-01-08 using JavaScript? Thank you! Edit: I was working with ExtJS and discovered that there's an easier way to achiev ...

Element is missing the necessary "key" property. (React and TypeScript)

Upon running the following code for reactJS and typescript, I encountered the error below: I have also included the import statement import 'bootstrap/dist/css/bootstrap.min.css'; in Index.tsx. Is there a solution to resolve this issue? npm s ...

Unable to get PrependTo to remove itself when clicked

Below is a custom jQuery script I put together: $(function(){ $("a img").click(function() { $("<div id=\"overlay\"></div>").hide().prependTo("body").fadeIn(100); $("body").css({ ...

Tips for updating a specific portion of a component in react.js

import React,{useEffect} from 'react'; import CloudTables from '@cloudtables/react'; import { useState } from 'react'; function DataGridTable ({ input1Value, input2Value }) { return ( <div className="con ...

Strategies for Handling Various Versions of npm Modules within a Project when Multiple Packages Depend on Specific Versions Internally

I find myself in a predicament with my main React project using version "1.5.1" of "@material-ui/core", while attempting to build a new component that requires version "3.2.1" of "#@rjsf/material-ui" which internally relies on the latest version of "@mater ...

What is the equivalent of $.fn in AngularJS when using angular.element()?

Currently, I am conducting a directive unit test using jasmine. The test is now functional, but I need to find an alternative for $.fn in angularjs since the use of $ is prohibited in my workplace. Code: (function scrollTopEventDirective(application) ...

You cannot add properties to an object within an async function

I am attempting to include a fileUrl property in the order object within an async function, but I am unable to make it work properly. My expectation is for the order object to contain a fileUrl property once added, but unfortunately, it does not seem to b ...

What is the best way to choose the unique identifier of an HTML element inside a for loop in a Django template?

I need help selecting an HTML button that is generated within a for loop in a Django template using JavaScript. How can I assign a unique ID to each button and select it correctly in JavaScript? Currently, all buttons have the same ID within the loop, resu ...

What causes the Top Navbar in Twitter Bootstrap to exceed the container when fixed?

While working with the default fixed-top navbar in Bootstrap, I encountered an issue where it spans the full width of the viewport. In order to contain it within a specific container div, I tried applying a CSS override for the left side: .navbar-fixed-to ...

Is it possible to personalize CSS properties using PHP sessions?

Currently, I am a beginner in PHP and enrolled in a technical school class to learn more about it. Our latest assignment involves using sessions to modify four CSS properties: body background-color, a:link color, a:hover color, and h1 color. The task inclu ...

Altering CSS attribute values using a random number generator

Is there a way to randomly change the animation-duration attribute in the following CSS code? I want it to range from 0 to 1. @keyframes blink { 50% { border-color: #ff0000; } } p{ animation-name: blink ; animation-duration: 0.1s ; animatio ...

The live updates for user data in Firestore are not being reflected immediately when using valueChanges

Utilizing Angular and Cloud Firestore for my backend, I have a setup where users can follow or unfollow each other. The issue arises when the button text and list of followers/following do not immediately update on the front end after a successful click ev ...

Retrieve an HTML element that is a select option with jQuery

I have a select input containing different options as shown below: <select id="myArea"> <option class="myClass_1" style="color:red;" value="1">Area 1</option> <option class="myClass_2" style="color:green;" value="2">Area 2& ...

Resetting text in an input field using CSS

Here is the fiddle link for reference: http://jsfiddle.net/a765q/1/. I noticed that when I click the reset button, the text color changes to grey. Any ideas on how to fix this? ...