Multiple mouse:down events trigger in FabricJS

A unique script is utilized to retrieve JSON data through an AJAX request and display it on the Canvas. What makes this interesting is that there are various buttons on the webpage, each associated with a canvas element. When any of these buttons are clicked, a new AJAX request is triggered, leading to the rendering of the updated JSON data.

An issue arises during every other rendering process (quite peculiar). To illustrate, after the first render, the mouse:down event functions as expected. However, during the second render, it fires twice. Subsequently, on the third render, it works fine again, but on the fourth render, it fires twice once more, and so forth...

Below is the script executed upon clicking any button:

// The 'objects' variable stores the JSON objects retrieved from the AJAX request.
// These objects pertain to fabricJS elements.
var drawing = JSON.parse(objects);

for (var i = 0; i < drawing.objects.length; i++) {
    drawing.objects[i]['left'] += 50;
}

canvas.clear();
canvas.loadFromJSON(drawing, canvas.renderAll.bind(canvas));

canvas.setZoom(0.66);
canvas.setZoom(canvas.getZoom() * 1.3);

canvas.on('mouse:down', function (el) {
    console.log(el.target);
}

UPDATE: It seems that I inadvertently applied the same event listener repeatedly during each render. Consequently, this explains why the event fires multiple times on subsequent renders.

Answer №1

It is important to use canvas.off('mouse:down') before adding another mouse:down event to the canvas. This will ensure that only one event is active at a time. canvas.off function can be used to remove the previously attached event from the canvas.

DEMO

var canvas = new fabric.Canvas('c');
function addEvent(){
 canvas.on('mouse:down',function(){
  console.log('mouseDown');
 })
}
function removeEvent(){
 canvas.off('mouse:down');
}
canvas {
    border: 1px solid #999;
}
<script src="https://rawgithub.com/kangax/fabric.js/master/dist/fabric.js"></script>
<button onclick='addEvent()'>addEvent</button>
<button onclick='removeEvent()'>removeEvent</button>
<canvas id="c" width="500" height="500"></canvas>

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

The transfer of JSON data to PHP through AJAX is not successful

I have encountered an issue while attempting to send a JSON string to a PHP file using ajax. The problem lies in the variable I am posting not being delivered when employing the JQUERY ajax method as illustrated below: <DOCTYPE html> <html> ...

Retrieve the data value from a click event using the class identifier

The following code will display the correct class name, but not the correct data-validamount. It will only show: undefined. $(".prod_amount_add").click(function(){ var rowAmount = 0; var datavalid = $(this).attr('data-validamount'); ...

What is the best way to remove an active item from a Vue v-list?

When using Vuetify's v-list-item directive, I encountered an issue where the active prop cannot be removed once an item has been selected. Here is my approach so far: <v-list-item-group pb-6 color="primary" class="pb-3 text-left"> ...

Managing various swipe interactions using HTML and JavaScript/jQuery

I'm in the process of creating a mobile multiplayer game using HTML5 and Javascript. The jQuery Plugin "touchwipe" is utilized to manage swipe events in various divs like this: $('#play1').touchwipe({ wipeLeft: function(){ if ...

Encountering an issue when utilizing a personalized directive with AngularJS

I'm encountering an issue with the "auto-complete" directive that I'm using from jsfiddle. The error message I'm receiving is iElement.autocomplete is not a function. Can someone help me troubleshoot and fix this error? directive.js starte ...

I am interested in accessing a file located on my D: drive through the use of AJAX

The file I uploaded can be found at D:\eclipseworkspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\DatasetFileUpload\myNewFolder However, I am having trouble reading a file from the above locati ...

Showing information retrieved from an API and rendering it on an HTML page

My aim is to showcase a list of calculated results fetched from a local server. In the console, this data appears as an array of objects, but on the webpage, it is being displayed as separate string characters for each li element. How can I display the con ...

Add some text onto the Box Component in Material UI

I am looking to replicate the hover functionality (UI) seen in this example: Desired UI Source: Since adjusting background image styles can be complex, I have opted to use the Box Component from Material UI. Within the Box Component, I have implemented th ...

Dynamic class/interface in Typescript (using Angular)

Is there a way to achieve intellisense for an object created with a dynamic class by passing parameters? Here is the code snippet: Main: let ita: any = new DynamicClass('ITA'); let deu: any = new DynamicClass('DEU'); The DynamicClass ...

Troubleshooting Rails 5 and AJAX modal login issues

In my pursuit of implementing ajax authorization in Rails 5.0.0, I have tried numerous guides without success. Here's what I've done: 1. Cloned the Devise Controllers Users::SessionsController < Devise::SessionsController def create re ...

Modifying the label of the Yes/No button in a jqdialog

Is it possible to customize the captions of Yes-No buttons within a jqdialog box using jQuery? ...

Error encountered while using Google Translate with XMLHttpRequest (Missing 'Access-Control-Allow-Origin' header)

Trying to access a page that utilizes Google Translate is resulting in the following error: XMLHttpRequest cannot load http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit. No 'Access-Control-Allow-Origin' heade ...

Loading data using AJAX for insertion during page load

I'm attempting to insert data into a database using PHP, but I'm struggling to figure out how to accomplish this task. Despite conducting searches on Google, I have yet to find a suitable solution. Here is my Ajax code: if(window.location == "p ...

Exploring the process of reading a file from a specified file path within a text area using jQuery

I am looking for a way to dynamically read a file based on its path, and then display the contents of that file in a text area. I have attempted to do this with the following code, but it is not working as expected. Here is the code snippet: goog ...

An issue has been identified in the bubble sort algorithm causing certain numerical lists to not be properly sorted when implemented in NodeJS

I am just beginning to learn about algorithms and have started with the bubble sort. I wrote my own implementation and it seems to work well most of the time when sorting a list of numbers from 1 to 100. However, occasionally there is one random number th ...

Troubleshooting problem: Implementing MVC framework with Ajax and jQuery for form submission

I am currently working with MVC 4 and have encountered an issue while submitting an Ajax form. The form successfully updates the model database, but when I try to update the form, instead of closing the jQuery dialog as expected, I am redirected to a blank ...

How can I prevent the modal from appearing each time I navigate back to the page where it is displayed from another page?

Currently, I am in the process of developing a web application using Node.js with Express, Mongoose, and EJS. One of the key features of my app is a modal that appears after a user logs in or signs up, then redirects to the dashboard page. This modal displ ...

What is the reason for the blank first page when printing with vue-html2pdf, a tool that utilizes html2pdf.js internally?

Hey there, I'm currently experiencing issues with printing using a Vue component named vue-html2pdf. Here are the problems I'm facing: The pagination doesn't break the page when content is added, resulting in a 3-page printout. The first p ...

Separate string by using a regular expression pattern

Looking to parse a dynamic string with varying combinations of Code, Name, and EffectDate. It could be in the format below with all three properties or just pairs like Code-Name, Code-EffectDate, or Name-EffectDate. {"Code":{"value":"1"},"Name":{"value": ...

Material-UI Scroll Dialog that begins scrolling from the bottom

While attempting to incorporate a scrolling div with the ref tag inside Dialog Material-UI Design, I encountered an error stating Cannot read property 'scrollHeight' of undefined When running my code outside of the Dialog, it functions correctly ...