What are Fabric.js tools for "Drop Zones"?

Has anyone successfully created a "drop zone" similar to interact.js using fabric.js?

I haven't had the chance to experiment with it myself. I have some ideas on how I could potentially implement it, but before diving in, I wanted to see if anyone else has done something similar. My Google searches so far haven't turned up anything useful.

*Note: I'd prefer not to add another library just for this specific functionality. While I know I could use interact.js, I'm hoping to avoid adding unnecessary dependencies if possible.


Answer:

For those seeking a solution... You could potentially achieve this using isContainedWithinObject(other, absoluteopt, calculateopt) → {Boolean} method in fabric.js. After going through the fabric.js documentation, I realized that drawing 9 rectangles (top left, top center, top right, middle left, middle center, middle right, bottom left, bottom center, and bottom right) and running the method on the appropriate objects might do the trick.

Answer №1

If you want to create a dropzone using CSS and a classic input method, you can style it as shown in the snippet below.

var canvas = new fabric.Canvas('canvas');
canvas.setHeight(300);
canvas.setWidth(400);

document.querySelector("#pdf-upload").addEventListener("change", function(e) {
  var file = e.target.files[0]
  if (file.type == "image/jpeg" || "image/png") {
    var reader = new FileReader();
    reader.onload = function(event) {
      var data = event.target.result;
      fabric.Image.fromURL(data, function(image) {
        var imageObject = image;
        canvas.setBackgroundImage(imageObject);
        imageObject.scaleToHeight(300);
        canvas.renderAll();
      });
    };
    reader.readAsDataURL(file);
  };
  $("#canvas").css("visibility", "visible");
  $(".dz").css("visibility", "hidden");
});
.dz-text {
  position: absolute;
  left: 50%;
  margin-left: -100px;
  top: 50%;
  width: 200px;
  text-align: center;
}

.dz-button {
  position: absolute;
  top: 50%;
  margin-top: -50px;
  left: 50%;
  z-index: 3;
  margin-left: -150px;
  width: 300px;
  position: absolute;
  padding: 120px 0 0 0;
  height: 100px;
  overflow: hidden;
  border: dotted 5px black;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  border-radius: 20px;
  background-size: 60px 60px;
  background-color: rgba(155, 105, 255, 0.2);
  background-clip: padding-box;
}

.dz-button:hover {
  background-color: rgba(155, 105, 255, 0.3);
}

#canvas {
  border: solid 1px black;
  z-index: 1;
  visibility: hidden;
}
<html>

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.4.0/fabric.js"></script>
</head>

<body>
  <div class="dz">
    <div class="dz-text"><b>Drop image here</b></div>
    <input class="dz-button" id="pdf-upload" type="file">
  </div>

  <canvas id="canvas"></canvas>
</body>

</html>

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

What is the best way to create vertical spacing between Material UI Grid Paper components?

The spacing of the goal components is not as I would like it to be. This is how they currently appear. https://i.stack.imgur.com/jApzK.png So far, I have attempted setting the display of the Paper selector to flex. Additionally, I experimented with adjus ...

Confidently set up a proxy that is recursively nested and strongly typed

I have a collection of objects where I store various content for a user interface. Here is an example: const copy = { header: { content: 'Page Header' }, main: { header: { content: 'Content Subheader' }, body ...

Unleash the power of a module by exposing it to the global Window object using the dynamic

In my development process, I am utilizing webpack to bundle and manage my TypeScript modules. However, I am facing a challenge where I need certain modules or chunks to be accessible externally. Can anyone guide me on how to achieve this? Additional conte ...

The function signature '(_event: React.SyntheticEvent, value: number) => void' cannot be assigned to the type 'FormEventHandler<HTMLUListElement>'

I am facing an issue with my component "PageFooter" being duplicated in three other components. I am trying to refactor it as a UI component. " I am getting the error message: 'Type '(_event: React.SyntheticEvent, value: number) = ...

JavaScript doesn't automatically redirect after receiving a response

Hey there, I'm attempting to implement a redirect upon receiving a response from an ajax request. However, it seems that the windows.href.location doesn't execute the redirect until the PHP background process finishes processing. Check out my cod ...

Firebase Error: Trying to access properties of null object (indexOf)

Whenever I try to console.log(docSnap), a Firebase error shows up as seen in the image below. Despite attempting various solutions, none have proved effective. useEffect(() => { if (folderId === null) { dispatch({ ...

Creating a dynamic nested list in HTML using JavaScript with data retrieved from a JSON source

I'm trying to generate a dynamic nested ul\li list from a JSON array. IMPORTANT! While I can use jQuery for this transformation, it's in a node.js environment where DOM access is restricted and I must work with a string. The depth of the a ...

The Ajax data was not displayed in the console log, instead an error message was returned stating "http://localhost/IFICSV3/public/sla/sla/getbranch/180 not found"

I am attempting to make a dropdown option dependent on another using ajax. I want to view the data in the console to see if it is successful or not. I expect the data to be displayed in the console log, but instead, an error is being given. http://local ...

Using the NodeJS driver for MongoDB to Update Documents

I'm currently working on updating a document using the MongoDB Node.js driver, without utilizing Mongoose. However, I keep receiving an undefined result for the updated document. I'm struggling to pinpoint what might be causing this issue. var M ...

The browser message states: Variable $? Not Found

As a newcomer to javascript (jquery/json), I've created code to display a chart using CanvasJS with a php/json data fetching script. However, I'm facing an issue where the chart is not rendering when I integrate my code. Upon inspecting the brows ...

Tips for swapping out a sticky element as you scroll

Context As I work on developing a blog website, I aim to integrate a sticky element that dynamically updates according to the current year and month as users scroll through the content. This would provide a visual indication of the timeline for the listed ...

Automatically generated VueJS function

Creating a logging system for my Javascript Project using VueJS and Vuex To make logging methods accessible to all components, I am utilizing a global Mixin : import { mapState, mapActions } from 'vuex' import LogLevel from '@/enums/logger ...

Utilizing AngularJS: Triggering a controller function from a directive

I am currently working on a project with a model named 'user', which includes a controller called 'login' and a directive called 'userMenu'. My goal is to have the userMenu directive utilize the 'login' controller th ...

Display the user's input value in a tooltip without using jQuery

I am looking to achieve this particular layout design. https://i.stack.imgur.com/p9UTH.jpg I am unsure about how to display the input value in the bubble within this layout. The visibility of the bubble should only be triggered on hover. Below is the cod ...

Switch between two PHP files with a toggle feature using jQuery click event

Need help with toggling between two PHP files - cab.php and d3.php. Toggling within the same file works fine, but encountering issues when trying to toggle from one file to another. function botaod2mostraesconde() { $(".wrapd2").toggle(); $( ...

Tips on preventing flickering when using javascript for drag and drop functionality

I have implemented the following JavaScript code (using jQuery) to manage drag and drop functionality in a script I am developing: jsc.ui.dragging = false; jsc.ui.drag_element = {}; $(".drag-target").mousedown(function() { jsc.ui.drag_element = $(thi ...

subscribing to multiple observables, such as an observable being nested within another observable related to HTTP requests

Hello, I recently started learning Angular and I am facing a challenge with posting and getting data at the same time. I am currently using the map function and subscribing to the observable while also having an outer observable subscribed in my component. ...

Using Javascript, delete all chosen HTML elements containing innerText

Looking to extract certain HTML tags from a block of code in TextArea1 and display the modified output in TextArea2 upon clicking a button. <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8&quo ...

What is the reason behind FieldSelect returning a string instead of an object like FieldCheckbox?

FieldSelect component from Sharetribe documents is giving me a string, while FieldCheckbox is returning a JSON object. In a specific scenario, I want FieldSelect to store a JSON object. How can I achieve this? Below is the code snippet for reference: I& ...

Why is the 3rd argument necessary when using useReducer?

According to the information provided in the documentation: [init, the 3d argument] allows you to separate the logic for determining the initial state outside of the reducer. This is particularly useful for resetting the state later in response to an ac ...